/*
 * Copyright (C) Ascensio System SIA 2012-2019. All rights reserved
 *
 * https://www.onlyoffice.com/
 *
 * Version: 0.0.0 (build:0)
 */

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
var AscBrowser = {
    userAgent : "",
    isIE : false,
    isMacOs : false,
    isSafariMacOs : false,
    isAppleDevices : false,
    isAndroid : false,
    isMobile : false,
    isGecko : false,
    isChrome : false,
    isOpera : false,
    isWebkit : false,
    isSafari : false,
    isArm : false,
    isMozilla : false,
	isRetina : false,
    isLinuxOS : false,
	retinaPixelRatio : 1,
	isVivaldiLinux : false
};

// user agent lower case
AscBrowser.userAgent = navigator.userAgent.toLowerCase();

// ie detect
AscBrowser.isIE =  (AscBrowser.userAgent.indexOf("msie") > -1 ||
                    AscBrowser.userAgent.indexOf("trident") > -1 ||
					AscBrowser.userAgent.indexOf("edge") > -1);

AscBrowser.isIeEdge = (AscBrowser.userAgent.indexOf("edge/") > -1);

AscBrowser.isIE9 =  (AscBrowser.userAgent.indexOf("msie9") > -1 || AscBrowser.userAgent.indexOf("msie 9") > -1);
AscBrowser.isIE10 =  (AscBrowser.userAgent.indexOf("msie10") > -1 || AscBrowser.userAgent.indexOf("msie 10") > -1);

// macOs detect
AscBrowser.isMacOs = (AscBrowser.userAgent.indexOf('mac') > -1);

// chrome detect
AscBrowser.isChrome = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("chrome") > -1);

// safari detect
AscBrowser.isSafari = !AscBrowser.isIE && !AscBrowser.isChrome && (AscBrowser.userAgent.indexOf("safari") > -1);

// macOs safari detect
AscBrowser.isSafariMacOs = (AscBrowser.isSafari && AscBrowser.isMacOs);

// apple devices detect
AscBrowser.isAppleDevices = (AscBrowser.userAgent.indexOf("ipad") > -1 ||
                             AscBrowser.userAgent.indexOf("iphone") > -1 ||
                             AscBrowser.userAgent.indexOf("ipod") > -1);

// android devices detect
AscBrowser.isAndroid = (AscBrowser.userAgent.indexOf("android") > -1);

// mobile detect
AscBrowser.isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);

// gecko detect
AscBrowser.isGecko = (AscBrowser.userAgent.indexOf("gecko/") > -1);

// opera detect
AscBrowser.isOpera = (!!window.opera || AscBrowser.userAgent.indexOf("opr/") > -1);

// webkit detect
AscBrowser.isWebkit = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("webkit") > -1);

// arm detect
AscBrowser.isArm = (AscBrowser.userAgent.indexOf("arm") > -1);

AscBrowser.isMozilla = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("firefox") > -1);

AscBrowser.isLinuxOS = (AscBrowser.userAgent.indexOf(" linux ") > -1);

AscBrowser.isVivaldiLinux = AscBrowser.isLinuxOS && (AscBrowser.userAgent.indexOf("vivaldi") > -1);

AscBrowser.zoom = 1;

AscBrowser.checkZoom = function()
{
    if (AscBrowser.isAndroid)
	{
		AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
		AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		return;
	}

	AscBrowser.zoom = 1.0;
	AscBrowser.isRetina = false;
	AscBrowser.retinaPixelRatio = 1;

    if (AscBrowser.isChrome && !AscBrowser.isOpera && !AscBrowser.isMobile && document && document.firstElementChild && document.body)
    {
        if (false)
		{
			// этот код - рабочий, но только если этот ифрейм открыт на весь размер браузера
            // (window.outerWidth и window.innerWidth зависимы)
			if (window.innerWidth > 300)
				AscBrowser.zoom = window.outerWidth / window.innerWidth;

			if (Math.abs(AscBrowser.zoom - 1) < 0.1)
				AscBrowser.zoom = 1;

			AscBrowser.zoom = window.outerWidth / window.innerWidth;

			var _devicePixelRatio = window.devicePixelRatio / AscBrowser.zoom;

			// device pixel ratio: кратно 0.5
			_devicePixelRatio = (5 * (((2.5 + 10 * _devicePixelRatio) / 5) >> 0)) / 10;

			AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
			if (2 == _devicePixelRatio)
				AscBrowser.isRetina = true;

			// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
			//document.firstElementChild.style.zoom = "reset";
			document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
		}
		else
        {
            // делаем простую проверку
            // считаем: 0 < window.devicePixelRatio < 2 => _devicePixelRatio = 1; zoom = window.devicePixelRatio / _devicePixelRatio;
			// считаем: window.devicePixelRatio >= 2 => _devicePixelRatio = 2; zoom = window.devicePixelRatio / _devicePixelRatio;
            if (window.devicePixelRatio > 0.1)
			{
				if (window.devicePixelRatio < 1.99)
				{
					var _devicePixelRatio = 1;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
				}
				else
				{
					var _devicePixelRatio = 2;
					AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
					AscBrowser.isRetina = true;
				}
				// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
				//document.firstElementChild.style.zoom = "reset";
				document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
			}
			else
				document.firstElementChild.style.zoom = "normal";
        }

        if (AscBrowser.isRetina)
        	AscBrowser.retinaPixelRatio = 2;
    }
    else
    {
		AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);
		if (AscBrowser.isRetina)
			AscBrowser.retinaPixelRatio = 2;

		if (AscBrowser.isMobile)
		{
			AscBrowser.isRetina = (window.devicePixelRatio >= 1.9);
			AscBrowser.retinaPixelRatio = window.devicePixelRatio;
		}
    }
};

AscBrowser.checkZoom();

AscBrowser.convertToRetinaValue = function(value, isScale)
{
	if (isScale === true)
		return ((value * AscBrowser.retinaPixelRatio) + 0.5) >> 0;
	else
		return ((value / AscBrowser.retinaPixelRatio) + 0.5) >> 0;
};

    //--------------------------------------------------------export----------------------------------------------------
    window['AscCommon'] = window['AscCommon'] || {};
    window['AscCommon'].AscBrowser = AscBrowser;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function(window, undefined)
{
	var g_cCharDelimiter      = String.fromCharCode(5);
	var g_cGeneralFormat      = 'General';
	var FONT_THUMBNAIL_HEIGHT = (7 * 96.0 / 25.4) >> 0;
	var c_oAscMaxColumnWidth  = 255;
	var c_oAscMaxRowHeight    = 409.5;
	var c_nMaxConversionTime  = 900000;//depends on config
	var c_nMaxDownloadTitleLen= 255;
	var c_nVersionNoBase64 = 10;
	var c_dMaxParaRunContentLength = 256;
	var c_rUneditableTypes = /^(?:(pdf|djvu|xps))$/;

	//files type for Saving & DownloadAs
	var c_oAscFileType = {
		UNKNOWN : 0,
		PDF     : 0x0201,
		PDFA    : 0x0901,
		HTML    : 0x0803,

		// Word
		DOCX : 0x0041,
		DOC  : 0x0042,
		ODT  : 0x0043,
		RTF  : 0x0044,
		TXT  : 0x0045,
		MHT  : 0x0047,
		EPUB : 0x0048,
		FB2  : 0x0049,
		MOBI : 0x004a,
		DOCY : 0x1001,
		CANVAS_WORD : 0x2001,
		JSON : 0x0808,	// Для mail-merge

		// Excel
		XLSX : 0x0101,
		XLS  : 0x0102,
		ODS  : 0x0103,
		CSV  : 0x0104,
		XLSY : 0x1002,

		// PowerPoint
		PPTX : 0x0081,
		PPT  : 0x0082,
		ODP  : 0x0083
	};

	var c_oAscError = {
		Level : {
			Critical   : -1,
			NoCritical : 0
		},
		ID    : {
			ServerSaveComplete   : 3,
			ConvertationProgress : 2,
			DownloadProgress     : 1,
			No                   : 0,
			Unknown              : -1,
			ConvertationTimeout  : -2,

			DownloadError        : -4,
			UnexpectedGuid       : -5,
			Database             : -6,
			FileRequest          : -7,
			FileVKey             : -8,
			UplImageSize         : -9,
			UplImageExt          : -10,
			UplImageFileCount    : -11,
			NoSupportClipdoard   : -12,
			UplImageUrl          : -13,


			MaxDataPointsError    : -16,
			StockChartError       : -17,
			CoAuthoringDisconnect : -18,
			ConvertationPassword  : -19,
			VKeyEncrypt           : -20,
			KeyExpire             : -21,
			UserCountExceed       : -22,
			AccessDeny            : -23,
			LoadingScriptError    : -24,

			SplitCellMaxRows     : -30,
			SplitCellMaxCols     : -31,
			SplitCellRowsDivider : -32,

			MobileUnexpectedCharCount : -35,

			// Mail Merge
			MailMergeLoadFile : -40,
			MailMergeSaveFile : -41,

			// for AutoFilter
			AutoFilterDataRangeError         : -50,
			AutoFilterChangeFormatTableError : -51,
			AutoFilterChangeError            : -52,
			AutoFilterMoveToHiddenRangeError : -53,
			LockedAllError                   : -54,
			LockedWorksheetRename            : -55,
			FTChangeTableRangeError          : -56,
			FTRangeIncludedOtherTables       : -57,

			PasteMaxRangeError   : -64,
			PastInMergeAreaError : -65,
			CopyMultiselectAreaError : -66,

			DataRangeError  : -72,
			CannotMoveRange : -71,

			MaxDataSeriesError : -80,
			CannotFillRange    : -81,

			ConvertationOpenError : -82,
            ConvertationSaveError : -83,

			UserDrop : -100,
			Warning  : -101,

			PrintMaxPagesCount					: -110,

			SessionAbsolute: -120,
			SessionIdle: -121,
			SessionToken: -122,

			/* для формул */
			FrmlWrongCountParentheses   : -300,
			FrmlWrongOperator           : -301,
			FrmlWrongMaxArgument        : -302,
			FrmlWrongCountArgument      : -303,
			FrmlWrongFunctionName       : -304,
			FrmlAnotherParsingError     : -305,
			FrmlWrongArgumentRange      : -306,
			FrmlOperandExpected         : -307,
			FrmlParenthesesCorrectCount : -308,
			FrmlWrongReferences         : -309,

			InvalidReferenceOrName : -310,
			LockCreateDefName      : -311,

			LockedCellPivot				: -312,

			ForceSaveButton: -331,
			ForceSaveTimeout: -332,

			OpenWarning : 500,

            DataEncrypted : -600,
		}
	};

	var c_oAscAsyncAction = {
		Open               : 0,  // открытие документа
		Save               : 1,  // сохранение
		LoadDocumentFonts  : 2,  // загружаем фонты документа (сразу после открытия)
		LoadDocumentImages : 3,  // загружаем картинки документа (сразу после загрузки шрифтов)
		LoadFont           : 4,  // подгрузка нужного шрифта
		LoadImage          : 5,  // подгрузка картинки
		DownloadAs         : 6,  // cкачать
		Print              : 7,  // конвертация в PDF и сохранение у пользователя
		UploadImage        : 8,  // загрузка картинки

		ApplyChanges : 9,  // применение изменений от другого пользователя.

		SlowOperation     : 11, // медленная операция
		LoadTheme         : 12, // загрузка темы
		MailMergeLoadFile : 13, // загрузка файла для mail merge
		DownloadMerge     : 14, // cкачать файл с mail merge
		SendMailMerge     : 15,  // рассылка mail merge по почте
		ForceSaveButton   : 16,
		ForceSaveTimeout  : 17
	};

	var c_oAscAdvancedOptionsID = {
		CSV : 0,
		TXT : 1,
		DRM : 2
	};

	var c_oAscAdvancedOptionsAction = {
		None : 0,
		Open : 1,
		Save : 2
	};

	var c_oAscRestrictionType = {
		None           : 0,
		OnlyForms      : 1,
		OnlyComments   : 2,
		OnlySignatures : 3,
		View           : 0xFF // Отличие данного ограничения от обычного ViewMode в том, что редактор открывается
		                      // как полноценный редактор, просто мы запрещаем ЛЮБОЕ редактирование. А во ViewMode
		                      // открывается именно просмотрщик.
	};

	// Режимы отрисовки
	var c_oAscFontRenderingModeType = {
		noHinting             : 1,
		hinting               : 2,
		hintingAndSubpixeling : 3
	};

	var c_oAscAsyncActionType = {
		Information      : 0,
		BlockInteraction : 1
	};

	var DownloadType = {
		None      : '',
		Download  : 'asc_onDownloadUrl',
		Print     : 'asc_onPrintUrl',
		MailMerge : 'asc_onSaveMailMerge'
	};

	var CellValueType = {
		Number : 0,
		String : 1,
		Bool   : 2,
		Error  : 3
	};

	/**
	 * NumFormat defines
	 * @enum {number}
	 */
	var c_oAscNumFormatType = {
		None       : -1,
		General    : 0,
		Number     : 1,
		Scientific : 2,
		Accounting : 3,
		Currency   : 4,
		Date       : 5,
		Time       : 6,
		Percent    : 7,
		Fraction   : 8,
		Text       : 9,
		Custom     : 10
	};

	var c_oAscDrawingLayerType = {
		BringToFront : 0,
		SendToBack   : 1,
		BringForward : 2,
		SendBackward : 3
	};

	var c_oAscCellAnchorType = {
		cellanchorAbsolute : 0,
		cellanchorOneCell  : 1,
		cellanchorTwoCell  : 2
	};

	var c_oAscChartDefines = {
		defaultChartWidth  : 478,
		defaultChartHeight : 286
	};

	var c_oAscStyleImage = {
		Default  : 0,
		Document : 1
	};

	var c_oAscTypeSelectElement = {
		Paragraph      : 0,
		Table          : 1,
		Image          : 2,
		Header         : 3,
		Hyperlink      : 4,
		SpellCheck     : 5,
		Shape          : 6,
		Slide          : 7,
		Chart          : 8,
		Math           : 9,
		MailMerge      : 10,
		ContentControl : 11
	};

	var c_oAscLineDrawingRule = {
		Left   : 0,
		Center : 1,
		Right  : 2,
		Top    : 0,
		Bottom : 2
	};

	var align_Right   = 0;
	var align_Left    = 1;
	var align_Center  = 2;
	var align_Justify = 3;


	var linerule_AtLeast = 0x00;
	var linerule_Auto    = 0x01;
	var linerule_Exact   = 0x02;

	var c_oAscShdClear = 0;
	var c_oAscShdNil   = 1;

	var vertalign_Baseline    = 0;
	var vertalign_SuperScript = 1;
	var vertalign_SubScript   = 2;
	var hdrftr_Header         = 0x01;
	var hdrftr_Footer         = 0x02;

	var c_oAscDropCap = {
		None   : 0x00,
		Drop   : 0x01,
		Margin : 0x02
	};


	var c_oAscChartTitleShowSettings = {
		none      : 0,
		overlay   : 1,
		noOverlay : 2
	};

	var c_oAscChartHorAxisLabelShowSettings = {
		none      : 0,
		noOverlay : 1
	};

	var c_oAscChartVertAxisLabelShowSettings = {
		none       : 0,
		rotated    : 1,
		vertical   : 2,
		horizontal : 3
	};

	var c_oAscChartLegendShowSettings = {
		none         : 0,
		left         : 1,
		top          : 2,
		right        : 3,
		bottom       : 4,
		leftOverlay  : 5,
		rightOverlay : 6,
		layout       : 7,
		topRight     : 8 // ToDo добавить в меню
	};

	var c_oAscChartDataLabelsPos = {
		none    : 0,
		b       : 1,
		bestFit : 2,
		ctr     : 3,
		inBase  : 4,
		inEnd   : 5,
		l       : 6,
		outEnd  : 7,
		r       : 8,
		t       : 9
	};

	var c_oAscChartCatAxisSettings = {
		none        : 0,
		leftToRight : 1,
		rightToLeft : 2,
		noLabels    : 3
	};

	var c_oAscChartValAxisSettings = {
		none      : 0,
		byDefault : 1,
		thousands : 2,
		millions  : 3,
		billions  : 4,
		log       : 5
	};

	var c_oAscAxisTypeSettings = {
		vert : 0,
		hor  : 1
	};

	var c_oAscGridLinesSettings = {
		none       : 0,
		major      : 1,
		minor      : 2,
		majorMinor : 3
	};


	var c_oAscChartTypeSettings = {
		barNormal              : 0,
		barStacked             : 1,
		barStackedPer          : 2,
		barNormal3d            : 3,
		barStacked3d           : 4,
		barStackedPer3d        : 5,
		barNormal3dPerspective : 6,
		lineNormal             : 7,
		lineStacked            : 8,
		lineStackedPer         : 9,
		lineNormalMarker       : 10,
		lineStackedMarker      : 11,
		lineStackedPerMarker   : 12,
		line3d                 : 13,
		pie                    : 14,
		pie3d                  : 15,
		hBarNormal             : 16,
		hBarStacked            : 17,
		hBarStackedPer         : 18,
		hBarNormal3d           : 19,
		hBarStacked3d          : 20,
		hBarStackedPer3d       : 21,
		areaNormal             : 22,
		areaStacked            : 23,
		areaStackedPer         : 24,
		doughnut               : 25,
		stock                  : 26,
		scatter                : 27,
		scatterLine            : 28,
		scatterLineMarker      : 29,
		scatterMarker          : 30,
		scatterNone            : 31,
		scatterSmooth          : 32,
		scatterSmoothMarker    : 33,
		surfaceNormal          : 34,
		surfaceWireframe       : 35,
		contourNormal          : 36,
		contourWireframe       : 37,
		unknown                : 38
	};


	var c_oAscValAxisRule = {
		auto  : 0,
		fixed : 1
	};

	var c_oAscValAxUnits = {
		none              : 0,
		BILLIONS          : 1,
		HUNDRED_MILLIONS  : 2,
		HUNDREDS          : 3,
		HUNDRED_THOUSANDS : 4,
		MILLIONS          : 5,
		TEN_MILLIONS      : 6,
		TEN_THOUSANDS     : 7,
		TRILLIONS         : 8,
		CUSTOM            : 9,
		THOUSANDS         : 10

	};

	var c_oAscTickMark = {
		TICK_MARK_CROSS : 0,
		TICK_MARK_IN    : 1,
		TICK_MARK_NONE  : 2,
		TICK_MARK_OUT   : 3
	};

	var c_oAscTickLabelsPos = {
		TICK_LABEL_POSITION_HIGH    : 0,
		TICK_LABEL_POSITION_LOW     : 1,
		TICK_LABEL_POSITION_NEXT_TO : 2,
		TICK_LABEL_POSITION_NONE    : 3
	};

	var c_oAscCrossesRule = {
		auto     : 0,
		maxValue : 1,
		value    : 2,
		minValue : 3
	};

	var c_oAscHorAxisType = {
		auto : 0,
		date : 1,
		text : 2
	};

	var c_oAscBetweenLabelsRule = {
		auto   : 0,
		manual : 1
	};

	var c_oAscLabelsPosition = {
		byDivisions      : 0,
		betweenDivisions : 1
	};


	var c_oAscAxisType = {
		auto : 0,
		date : 1,
		text : 2,
		cat  : 3,
		val  : 4
	};

	var c_oAscHAnchor = {
		Margin : 0x00,
		Page   : 0x01,
		Text   : 0x02,

		PageInternal : 0xFF // только для внутреннего использования
	};

	var c_oAscXAlign = {
		Center  : 0x00,
		Inside  : 0x01,
		Left    : 0x02,
		Outside : 0x03,
		Right   : 0x04
	};
	var c_oAscYAlign = {
		Bottom  : 0x00,
		Center  : 0x01,
		Inline  : 0x02,
		Inside  : 0x03,
		Outside : 0x04,
		Top     : 0x05
	};

	var c_oAscVAnchor = {
		Margin : 0x00,
		Page   : 0x01,
		Text   : 0x02
	};

	var c_oAscRelativeFromH = {
		Character     : 0x00,
		Column        : 0x01,
		InsideMargin  : 0x02,
		LeftMargin    : 0x03,
		Margin        : 0x04,
		OutsideMargin : 0x05,
		Page          : 0x06,
		RightMargin   : 0x07
	};

	var c_oAscSizeRelFromH = {
		sizerelfromhMargin        : 0,
		sizerelfromhPage          : 1,
		sizerelfromhLeftMargin    : 2,
		sizerelfromhRightMargin   : 3,
		sizerelfromhInsideMargin  : 4,
		sizerelfromhOutsideMargin : 5
	};

	var c_oAscSizeRelFromV = {
		sizerelfromvMargin        : 0,
		sizerelfromvPage          : 1,
		sizerelfromvTopMargin     : 2,
		sizerelfromvBottomMargin  : 3,
		sizerelfromvInsideMargin  : 4,
		sizerelfromvOutsideMargin : 5
	};

	var c_oAscRelativeFromV = {
		BottomMargin  : 0x00,
		InsideMargin  : 0x01,
		Line          : 0x02,
		Margin        : 0x03,
		OutsideMargin : 0x04,
		Page          : 0x05,
		Paragraph     : 0x06,
		TopMargin     : 0x07
	};

	// image wrap style
	var c_oAscWrapStyle = {
		Inline : 0,
		Flow   : 1
	};

	// Толщина бордера
	var c_oAscBorderWidth     = {
		None   : 0,	// 0px
		Thin   : 1,	// 1px
		Medium : 2,	// 2px
		Thick  : 3		// 3px
	};
	/**
	 * Располагаются в порядке значимости для отрисовки
	 * @enum {number}
	 */
	var c_oAscBorderStyles    = {
		None             : 0,
		Double           : 1,
		Hair             : 2,
		DashDotDot       : 3,
		DashDot          : 4,
		Dotted           : 5,
		Dashed           : 6,
		Thin             : 7,
		MediumDashDotDot : 8,
		SlantDashDot     : 9,
		MediumDashDot    : 10,
		MediumDashed     : 11,
		Medium           : 12,
		Thick            : 13
	};
	var c_oAscBorderType      = {
		Hor  : 1,
		Ver  : 2,
		Diag : 3
	};
	// PageOrientation
	var c_oAscPageOrientation = {
		PagePortrait  : 0x00,
		PageLandscape : 0x01
	};
	/**
	 * lock types
	 * @const
	 */
	var c_oAscLockTypes       = {
		kLockTypeNone   : 1, // никто не залочил данный объект
		kLockTypeMine   : 2, // данный объект залочен текущим пользователем
		kLockTypeOther  : 3, // данный объект залочен другим(не текущим) пользователем
		kLockTypeOther2 : 4, // данный объект залочен другим(не текущим) пользователем (обновления уже пришли)
		kLockTypeOther3 : 5  // данный объект был залочен (обновления пришли) и снова стал залочен
	};

	var c_oAscFormatPainterState = {
		kOff      : 0,
		kOn       : 1,
		kMultiple : 2
	};

	var c_oAscSaveTypes = {
		PartStart   : 0,
		Part        : 1,
		Complete    : 2,
		CompleteAll : 3
	};

	var c_oAscColor = {
		COLOR_TYPE_NONE   : 0,
		COLOR_TYPE_SRGB   : 1,
		COLOR_TYPE_PRST   : 2,
		COLOR_TYPE_SCHEME : 3,
		COLOR_TYPE_SYS    : 4
	};

	var c_oAscFill = {
		FILL_TYPE_NONE   : 0,
		FILL_TYPE_BLIP   : 1,
		FILL_TYPE_NOFILL : 2,
		FILL_TYPE_SOLID  : 3,
		FILL_TYPE_GRAD   : 4,
		FILL_TYPE_PATT   : 5,
		FILL_TYPE_GRP    : 6
	};

	// Chart defines
	var c_oAscChartType    = {
		line     : "Line",
		bar      : "Bar",
		hbar     : "HBar",
		area     : "Area",
		pie      : "Pie",
		scatter  : "Scatter",
		stock    : "Stock",
		doughnut : "Doughnut"
	};
	var c_oAscChartSubType = {
		normal     : "normal",
		stacked    : "stacked",
		stackedPer : "stackedPer"
	};

	var c_oAscFillGradType = {
		GRAD_LINEAR : 1,
		GRAD_PATH   : 2
	};
	var c_oAscFillBlipType = {
		STRETCH : 1,
		TILE    : 2
	};
	var c_oAscStrokeType   = {
		STROKE_NONE  : 0,
		STROKE_COLOR : 1
	};

	var c_oAscVAlign = {
		Bottom : 0, // (Text Anchor Enum ( Bottom ))
		Center : 1, // (Text Anchor Enum ( Center ))
		Dist   : 2, // (Text Anchor Enum ( Distributed ))
		Just   : 3, // (Text Anchor Enum ( Justified ))
		Top    : 4  // Top
	};

	var c_oAscVertDrawingText = {
		normal  : 1,
		vert    : 3,
		vert270 : 4
	};
	var c_oAscLineJoinType    = {
		Round : 1,
		Bevel : 2,
		Miter : 3
	};
	var c_oAscLineCapType     = {
		Flat   : 0,
		Round  : 1,
		Square : 2
	};
	var c_oAscLineBeginType   = {
		None     : 0,
		Arrow    : 1,
		Diamond  : 2,
		Oval     : 3,
		Stealth  : 4,
		Triangle : 5
	};
	var c_oAscLineBeginSize   = {
		small_small : 0,
		small_mid   : 1,
		small_large : 2,
		mid_small   : 3,
		mid_mid     : 4,
		mid_large   : 5,
		large_small : 6,
		large_mid   : 7,
		large_large : 8
	};
	var c_oAscCsvDelimiter    = {
		None      : 0,
		Tab       : 1,
		Semicolon : 2,
		Colon     : 3,
		Comma     : 4,
		Space     : 5
	};
	var c_oAscUrlType         = {
		Invalid : 0,
		Http    : 1,
		Email   : 2
	};

	var c_oAscCellTextDirection = {
		LRTB : 0x00,
		TBRL : 0x01,
		BTLR : 0x02
	};

	var c_oAscDocumentUnits = {
		Millimeter : 0,
		Inch       : 1,
		Point      : 2
	};

	var c_oAscMouseMoveDataTypes = {
		Common       : 0,
		Hyperlink    : 1,
		LockedObject : 2,
		Footnote     : 3
	};

	// selection type
	var c_oAscSelectionType = {
		RangeCells     : 1,
		RangeCol       : 2,
		RangeRow       : 3,
		RangeMax       : 4,
		RangeImage     : 5,
		RangeChart     : 6,
		RangeShape     : 7,
		RangeShapeText : 8,
		RangeChartText : 9,
		RangeFrozen    : 10
	};
	var c_oAscInsertOptions = {
		InsertCellsAndShiftRight : 1,
		InsertCellsAndShiftDown  : 2,
		InsertColumns            : 3,
		InsertRows               : 4,
		InsertTableRowAbove      : 5,
		InsertTableRowBelow      : 6,
		InsertTableColLeft       : 7,
		InsertTableColRight      : 8
	};

	var c_oAscDeleteOptions = {
		DeleteCellsAndShiftLeft : 1,
		DeleteCellsAndShiftTop  : 2,
		DeleteColumns           : 3,
		DeleteRows              : 4,
		DeleteTable             : 5
	};


	// Print default options (in mm)
	var c_oAscPrintDefaultSettings = {
		// Размеры страницы при печати
		PageWidth       : 210,
		PageHeight      : 297,
		PageOrientation : c_oAscPageOrientation.PagePortrait,

		// Поля для страницы при печати
		PageLeftField   : 17.8,
		PageRightField  : 17.8,
		PageTopField    : 19.1,
		PageBottomField : 19.1,
		MinPageLeftField	: 0.17,
		MinPageRightField	: 0.17,
		MinPageTopField		: 0.17,
		MinPageBottomField	: 0.17,

		PageGridLines : 0,
		PageHeadings  : 0
	};

	var c_oZoomType = {
		FitToPage  : 1,
		FitToWidth : 2,
		CustomMode : 3
	};

	var c_oNotifyType = {
		Dirty: 0,
		Shift: 1,
		Move: 2,
		Delete: 3,
		RenameTableColumn: 4,
		ChangeDefName: 5,
		ChangeSheet: 6,
		DelColumnTable: 7,
		Prepare: 8
	};

	var c_oNotifyParentType = {
		Change: 0,
		ChangeFormula: 1,
		EndCalculate: 2,
		GetRangeCell: 3,
		IsDefName: 4,
		Shared: 5
	};

	var c_oDashType = {
		dash          : 0,
		dashDot       : 1,
		dot           : 2,
		lgDash        : 3,
		lgDashDot     : 4,
		lgDashDotDot  : 5,
		solid         : 6,
		sysDash       : 7,
		sysDashDot    : 8,
		sysDashDotDot : 9,
		sysDot        : 10
	};


    /** @enum {number} */
    var c_oAscMathInterfaceType = {
        Common        : 0x00,
        Fraction      : 0x01,
        Script        : 0x02,
        Radical       : 0x03,
        LargeOperator : 0x04,
        Delimiter     : 0x05,
        Function      : 0x06,
        Accent        : 0x07,
        BorderBox     : 0x08,
        Bar           : 0x09,
        Box           : 0x0a,
        Limit         : 0x0b,
        GroupChar     : 0x0c,
        Matrix        : 0x0d,
        EqArray       : 0x0e,
        Phantom       : 0x0f
    };


	/** @enum {number} */
	var c_oAscMathInterfaceBarPos = {
		Top    : 0,
		Bottom : 1
	};

	/** @enum {number} */
	var c_oAscMathInterfaceScript = {
		None      : 0x000,  // Удаление скрипта
		Sup       : 0x001,
		Sub       : 0x002,
		SubSup    : 0x003,
		PreSubSup : 0x004
	};

	/** @enum {number} */
	var c_oAscMathInterfaceFraction = {
		Bar    : 0x001,
		Skewed : 0x002,
		Linear : 0x003,
		NoBar  : 0x004
	};

	/** @enum {number} */
	var c_oAscMathInterfaceLimitPos = {
		None   : -1,  // Удаление предела
		Top    : 0,
		Bottom : 1
	};

	/** @enum {number} */
	var c_oAscMathInterfaceMatrixMatrixAlign = {
		Top    : 0,
		Center : 1,
		Bottom : 2
	};

	/** @enum {number} */
	var c_oAscMathInterfaceMatrixColumnAlign = {
		Left   : 0,
		Center : 1,
		Right  : 2
	};

	/** @enum {number} */
	var c_oAscMathInterfaceEqArrayAlign = {
		Top    : 0,
		Center : 1,
		Bottom : 2
	};

	/** @enum {number} */
	var c_oAscMathInterfaceNaryLimitLocation = {
		UndOvr : 0,
		SubSup : 1
	};

	/** @enum {number} */
	var c_oAscMathInterfaceGroupCharPos = {
		None   : -1,  // Удаление GroupChar
		Top    : 0,
		Bottom : 1
	};

	var c_oAscTabLeader = {
		Dot        : 0x00,
		Heavy      : 0x01,
		Hyphen     : 0x02,
		MiddleDot  : 0x03,
		None       : 0x04,
		Underscore : 0x05
	};

	var c_oAscEncodings    = [
		[0, 28596, "ISO-8859-6", "Arabic (ISO 8859-6)"],
		[1, 720, "DOS-720", "Arabic (OEM 720)"],
		[2, 1256, "windows-1256", "Arabic (Windows)"],

		[3, 28594, "ISO-8859-4", "Baltic (ISO 8859-4)"],
		[4, 28603, "ISO-8859-13", "Baltic (ISO 8859-13)"],
		[5, 775, "IBM775", "Baltic (OEM 775)"],
		[6, 1257, "windows-1257", "Baltic (Windows)"],

		[7, 28604, "ISO-8859-14", "Celtic (ISO 8859-14)"],

		[8, 28595, "ISO-8859-5", "Cyrillic (ISO 8859-5)"],
		[9, 20866, "KOI8-R", "Cyrillic (KOI8-R)"],
		[10, 21866, "KOI8-U", "Cyrillic (KOI8-U)"],
		[11, 10007, "x-mac-cyrillic", "Cyrillic (Mac)"],
		[12, 855, "IBM855", "Cyrillic (OEM 855)"],
		[13, 866, "cp866", "Cyrillic (OEM 866)"],
		[14, 1251, "windows-1251", "Cyrillic (Windows)"],

		[15, 852, "IBM852", "Central European (OEM 852)"],
		[16, 1250, "windows-1250", "Central European (Windows)"],

		[17, 950, "Big5", "Chinese (Big5 Traditional)"],
		[18, 936, "GB2312", "Central (GB2312 Simplified)"],

		[19, 28592, "ISO-8859-2", "Eastern European (ISO 8859-2)"],

		[20, 28597, "ISO-8859-7", "Greek (ISO 8859-7)"],
		[21, 737, "IBM737", "Greek (OEM 737)"],
		[22, 869, "IBM869", "Greek (OEM 869)"],
		[23, 1253, "windows-1253", "Greek (Windows)"],

		[24, 28598, "ISO-8859-8", "Hebrew (ISO 8859-8)"],
		[25, 862, "DOS-862", "Hebrew (OEM 862)"],
		[26, 1255, "windows-1255", "Hebrew (Windows)"],

		[27, 932, "Shift_JIS", "Japanese (Shift-JIS)"],

		[28, 949, "KS_C_5601-1987", "Korean (Windows)"],
		[29, 51949, "EUC-KR", "Korean (EUC)"],

		[30, 861, "IBM861", "North European (Icelandic OEM 861)"],
		[31, 865, "IBM865", "North European (Nordic OEM 865)"],

		[32, 874, "windows-874", "Thai (TIS-620)"],

		[33, 28593, "ISO-8859-3", "Turkish (ISO 8859-3)"],
		[34, 28599, "ISO-8859-9", "Turkish (ISO 8859-9)"],
		[35, 857, "IBM857", "Turkish (OEM 857)"],
		[36, 1254, "windows-1254", "Turkish (Windows)"],

		[37, 28591, "ISO-8859-1", "Western European (ISO-8859-1)"],
		[38, 28605, "ISO-8859-15", "Western European (ISO-8859-15)"],
		[39, 850, "IBM850", "Western European (OEM 850)"],
		[40, 858, "IBM858", "Western European (OEM 858)"],
		[41, 860, "IBM860", "Western European (OEM 860 : Portuguese)"],
		[42, 863, "IBM863", "Western European (OEM 863 : French)"],
		[43, 437, "IBM437", "Western European (OEM-US)"],
		[44, 1252, "windows-1252", "Western European (Windows)"],

		[45, 1258, "windows-1258", "Vietnamese (Windows)"],

		[46, 65001, "UTF-8", "Unicode (UTF-8)"],
		[47, 65000, "UTF-7", "Unicode (UTF-7)"],

		[48, 1200, "UTF-16LE", "Unicode (UTF-16)"],
		[49, 1201, "UTF-16BE", "Unicode (UTF-16 Big Endian)"],

		[50, 12000, "UTF-32LE", "Unicode (UTF-32)"],
		[51, 12001, "UTF-32BE", "Unicode (UTF-32 Big Endian)"]
	];
	var c_oAscEncodingsMap = {
		"437"   : 43, "720" : 1, "737" : 21, "775" : 5, "850" : 39, "852" : 15, "855" : 12, "857" : 35, "858" : 40, "860" : 41, "861" : 30, "862" : 25, "863" : 42, "865" : 31, "866" : 13, "869" : 22, "874" : 32, "932" : 27, "936" : 18, "949" : 28, "950" : 17, "1200" : 48, "1201" : 49, "1250" : 16, "1251" : 14, "1252" : 44, "1253" : 23, "1254" : 36, "1255" : 26, "1256" : 2, "1257" : 6, "1258" : 45, "10007" : 11, "12000" : 50, "12001" : 51, "20866" : 9, "21866" : 10, "28591" : 37, "28592" : 19,
		"28593" : 33, "28594" : 3, "28595" : 8, "28596" : 0, "28597" : 20, "28598" : 24, "28599" : 34, "28603" : 4, "28604" : 7, "28605" : 38, "51949" : 29, "65000" : 47, "65001" : 46
	};
	var c_oAscCodePageNone = -1;
	var c_oAscCodePageUtf7 = 47;//65000
	var c_oAscCodePageUtf8 = 46;//65001
	var c_oAscCodePageUtf16 = 48;//1200
	var c_oAscCodePageUtf16BE = 49;//1201
	var c_oAscCodePageUtf32 = 50;//12000
	var c_oAscCodePageUtf32BE = 51;//12001

	// https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa?ui=en-US&rs=en-US&ad=US&fromAR=1
	var c_oAscMaxTooltipLength       = 256;
	var c_oAscMaxCellOrCommentLength = 32767;
	var c_oAscMaxFormulaLength       = 8192;

	var locktype_None   = 1; // никто не залочил данный объект
	var locktype_Mine   = 2; // данный объект залочен текущим пользователем
	var locktype_Other  = 3; // данный объект залочен другим(не текущим) пользователем
	var locktype_Other2 = 4; // данный объект залочен другим(не текущим) пользователем (обновления уже пришли)
	var locktype_Other3 = 5; // данный объект был залочен (обновления пришли) и снова стал залочен

	var changestype_None                      = 0; // Ничего не происходит с выделенным элементом (проверка идет через дополнительный параметр)
	var changestype_Paragraph_Content         = 1; // Добавление/удаление элементов в параграф
	var changestype_Paragraph_Properties      = 2; // Изменение свойств параграфа
	var changestype_Paragraph_AddText         = 3; // Добавление текста
	var changestype_Document_Content          = 10; // Добавление/удаление элементов в Document или в DocumentContent
	var changestype_Document_Content_Add      = 11; // Добавление элемента в класс Document или в класс DocumentContent
	var changestype_Document_SectPr           = 12; // Изменения свойств данной секции (размер страницы, поля и ориентация)
	var changestype_Document_Styles           = 13; // Изменяем стили документа (добавление/удаление/модифицирование)
	var changestype_Table_Properties          = 20; // Любые изменения в таблице
	var changestype_Table_RemoveCells         = 21; // Удаление ячеек (строк или столбцов)
	var changestype_Image_Properties          = 23; // Изменения настроек картинки
	var changestype_ContentControl_Remove     = 24; // Удаление контейнера целиком
	var changestype_ContentControl_Properties = 25; // Изменение свойств контейнера
	var changestype_ContentControl_Add        = 26; // Добавление контейнера
	var changestype_HdrFtr                    = 30; // Изменения в колонтитуле (любые изменения)
	var changestype_Remove                    = 40; // Удаление, через кнопку backspace (Удаление назад)
	var changestype_Delete                    = 41; // Удаление, через кнопку delete (Удаление вперед)
	var changestype_Drawing_Props             = 51; // Изменение свойств фигуры
	var changestype_ColorScheme               = 60; // Изменение свойств фигуры
	var changestype_Text_Props                = 61; // Изменение свойств фигуры
	var changestype_RemoveSlide               = 62; // Изменение свойств фигуры
	var changestype_PresentationProps         = 63; // Изменение темы, цветовой схемы, размера слайда;
	var changestype_Theme                     = 64; // Изменение темы;
	var changestype_SlideSize                 = 65; // Изменение цветовой схемы;
	var changestype_SlideBg                   = 66; // Изменение цветовой схемы;
	var changestype_SlideTiming               = 67; // Изменение цветовой схемы;
	var changestype_MoveComment               = 68;
	var changestype_AddSp                     = 69;
	var changestype_AddComment                = 70;
	var changestype_Layout                    = 71;
	var changestype_AddShape                  = 72;
	var changestype_AddShapes                 = 73;
	var changestype_PresDefaultLang           = 74;
	var changestype_SlideHide                 = 75;

	var changestype_2_InlineObjectMove       = 1; // Передвигаем объект в заданную позцию (проверяем место, в которое пытаемся передвинуть)
	var changestype_2_HdrFtr                 = 2; // Изменения с колонтитулом
	var changestype_2_Comment                = 3; // Работает с комментариями
	var changestype_2_Element_and_Type       = 4; // Проверяем возможно ли сделать изменение заданного типа с заданным элементом(а не с текущим)
	var changestype_2_ElementsArray_and_Type = 5; // Аналогично предыдущему, только идет массив элементов
	var changestype_2_AdditionalTypes        = 6; // Дополнительные проверки типа 1
	var changestype_2_Element_and_Type_Array = 7; // Проверяем возможно ли сделать изменения заданного типа с заданными элементами (для каждого элемента свое изменение)

	var contentchanges_Add    = 1;
	var contentchanges_Remove = 2;

	var PUNCTUATION_FLAG_BASE               = 0x0001;
	var PUNCTUATION_FLAG_CANT_BE_AT_BEGIN   = 0x0010;
	var PUNCTUATION_FLAG_CANT_BE_AT_END     = 0x0020;
	var PUNCTUATION_FLAG_EAST_ASIAN         = 0x0100;
	var PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E = 0x0002;
	var PUNCTUATION_FLAG_CANT_BE_AT_END_E   = 0x0004;

	var g_aPunctuation = [];
	g_aPunctuation[0x0021] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // !
	g_aPunctuation[0x0022] = PUNCTUATION_FLAG_BASE;                                     // "
	g_aPunctuation[0x0023] = PUNCTUATION_FLAG_BASE;                                     // #
	g_aPunctuation[0x0024] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // $
	g_aPunctuation[0x0025] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // %
	g_aPunctuation[0x0026] = PUNCTUATION_FLAG_BASE;                                     // &
	g_aPunctuation[0x0027] = PUNCTUATION_FLAG_BASE;                                     // '
	g_aPunctuation[0x0028] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // (
	g_aPunctuation[0x0029] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // )
	g_aPunctuation[0x002A] = PUNCTUATION_FLAG_BASE;                                     // *
	g_aPunctuation[0x002B] = PUNCTUATION_FLAG_BASE;                                     // +
	g_aPunctuation[0x002C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ,
	g_aPunctuation[0x002D] = PUNCTUATION_FLAG_BASE;                                     // -
	g_aPunctuation[0x002E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // .
	g_aPunctuation[0x002F] = PUNCTUATION_FLAG_BASE;                                     // /
	g_aPunctuation[0x003A] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // :
	g_aPunctuation[0x003B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ;
	g_aPunctuation[0x003C] = PUNCTUATION_FLAG_BASE;                                     // <
	g_aPunctuation[0x003D] = PUNCTUATION_FLAG_BASE;                                     // =
	g_aPunctuation[0x003E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // >
	g_aPunctuation[0x003F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ?
	g_aPunctuation[0x0040] = PUNCTUATION_FLAG_BASE;                                     // @
	g_aPunctuation[0x005B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // [
	g_aPunctuation[0x005C] = PUNCTUATION_FLAG_BASE;                                     // \
	g_aPunctuation[0x005D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ]
	g_aPunctuation[0x005E] = PUNCTUATION_FLAG_BASE;                                     // ^
	g_aPunctuation[0x005F] = PUNCTUATION_FLAG_BASE;                                     // _
	g_aPunctuation[0x0060] = PUNCTUATION_FLAG_BASE;                                     // `
	g_aPunctuation[0x007B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // {
	g_aPunctuation[0x007C] = PUNCTUATION_FLAG_BASE;                                     // |
	g_aPunctuation[0x007D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // }
	g_aPunctuation[0x007E] = PUNCTUATION_FLAG_BASE;                                     // ~

	g_aPunctuation[0x00A1] = PUNCTUATION_FLAG_BASE;                                     // ¡
	g_aPunctuation[0x00A2] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ¢
	g_aPunctuation[0x00A3] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // £
	g_aPunctuation[0x00A4] = PUNCTUATION_FLAG_BASE;                                     // ¤
	g_aPunctuation[0x00A5] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // ¥
	g_aPunctuation[0x00A6] = PUNCTUATION_FLAG_BASE;                                     // ¦
	g_aPunctuation[0x00A7] = PUNCTUATION_FLAG_BASE;                                     // §
	g_aPunctuation[0x00A8] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ¨
	g_aPunctuation[0x00A9] = PUNCTUATION_FLAG_BASE;                                     // ©
	g_aPunctuation[0x00AA] = PUNCTUATION_FLAG_BASE;                                     // ª
	g_aPunctuation[0x00AB] = PUNCTUATION_FLAG_BASE;                                     // «
	g_aPunctuation[0x00AC] = PUNCTUATION_FLAG_BASE;                                     // ¬
	g_aPunctuation[0x00AD] = PUNCTUATION_FLAG_BASE;                                     // ­
	g_aPunctuation[0x00AE] = PUNCTUATION_FLAG_BASE;                                     // ®
	g_aPunctuation[0x00AF] = PUNCTUATION_FLAG_BASE;                                     // ¯
	g_aPunctuation[0x00B0] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // °
	g_aPunctuation[0x00B1] = PUNCTUATION_FLAG_BASE;                                     // ±
	g_aPunctuation[0x00B4] = PUNCTUATION_FLAG_BASE;                                     // ´
	g_aPunctuation[0x00B6] = PUNCTUATION_FLAG_BASE;                                     // ¶
	g_aPunctuation[0x00B7] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ·
	g_aPunctuation[0x00B8] = PUNCTUATION_FLAG_BASE;                                     // ¸
	g_aPunctuation[0x00BA] = PUNCTUATION_FLAG_BASE;                                     // º
	g_aPunctuation[0x00BB] = PUNCTUATION_FLAG_BASE;                                     // »
	g_aPunctuation[0x00BB] = PUNCTUATION_FLAG_BASE;                                     // »
	g_aPunctuation[0x00BF] = PUNCTUATION_FLAG_BASE;                                     // ¿

	g_aPunctuation[0x2010] = PUNCTUATION_FLAG_BASE;                                     // ‐
	g_aPunctuation[0x2011] = PUNCTUATION_FLAG_BASE;                                     // ‑
	g_aPunctuation[0x2012] = PUNCTUATION_FLAG_BASE;                                     // ‒
	g_aPunctuation[0x2013] = PUNCTUATION_FLAG_BASE;                                     // –
	g_aPunctuation[0x2014] = PUNCTUATION_FLAG_BASE;                                     // —
	g_aPunctuation[0x2015] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ―
	g_aPunctuation[0x2016] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ‖
	g_aPunctuation[0x2017] = PUNCTUATION_FLAG_BASE;                                     // ‗
	g_aPunctuation[0x2018] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // ‘
	g_aPunctuation[0x2019] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ’
	g_aPunctuation[0x201A] = PUNCTUATION_FLAG_BASE;                                     // ‚
	g_aPunctuation[0x201B] = PUNCTUATION_FLAG_BASE;                                     // ‛
	g_aPunctuation[0x201C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // “
	g_aPunctuation[0x201D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ”
	g_aPunctuation[0x201E] = PUNCTUATION_FLAG_BASE;                                     // „
	g_aPunctuation[0x201F] = PUNCTUATION_FLAG_BASE;                                     // ‟
	g_aPunctuation[0x2020] = PUNCTUATION_FLAG_BASE;                                     // †
	g_aPunctuation[0x2021] = PUNCTUATION_FLAG_BASE;                                     // ‡
	g_aPunctuation[0x2022] = PUNCTUATION_FLAG_BASE;                                     // •
	g_aPunctuation[0x2023] = PUNCTUATION_FLAG_BASE;                                     // ‣
	g_aPunctuation[0x2024] = PUNCTUATION_FLAG_BASE;                                     // ․
	g_aPunctuation[0x2025] = PUNCTUATION_FLAG_BASE;                                     // ‥
	g_aPunctuation[0x2026] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // …
	g_aPunctuation[0x2027] = PUNCTUATION_FLAG_BASE;                                     // ‧
	g_aPunctuation[0x2030] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ‰
	g_aPunctuation[0x2031] = PUNCTUATION_FLAG_BASE;                                     // ‱
	g_aPunctuation[0x2032] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ′
	g_aPunctuation[0x2033] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ″
	g_aPunctuation[0x2034] = PUNCTUATION_FLAG_BASE;                                     // ‴
	g_aPunctuation[0x2035] = PUNCTUATION_FLAG_BASE;                                     // ‵
	g_aPunctuation[0x2036] = PUNCTUATION_FLAG_BASE;                                     // ‶
	g_aPunctuation[0x2037] = PUNCTUATION_FLAG_BASE;                                     // ‷
	g_aPunctuation[0x2038] = PUNCTUATION_FLAG_BASE;                                     // ‸
	g_aPunctuation[0x2039] = PUNCTUATION_FLAG_BASE;                                     // ‹
	g_aPunctuation[0x203A] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ›
	g_aPunctuation[0x203B] = PUNCTUATION_FLAG_BASE;                                     // ※
	g_aPunctuation[0x203C] = PUNCTUATION_FLAG_BASE;                                     // ‼
	g_aPunctuation[0x203D] = PUNCTUATION_FLAG_BASE;                                     // ‽
	g_aPunctuation[0x203E] = PUNCTUATION_FLAG_BASE;                                     // ‾
	g_aPunctuation[0x203F] = PUNCTUATION_FLAG_BASE;                                     // ‿
	g_aPunctuation[0x2040] = PUNCTUATION_FLAG_BASE;                                     // ⁀
	g_aPunctuation[0x2041] = PUNCTUATION_FLAG_BASE;                                     // ⁁
	g_aPunctuation[0x2042] = PUNCTUATION_FLAG_BASE;                                     // ⁂
	g_aPunctuation[0x2043] = PUNCTUATION_FLAG_BASE;                                     // ⁃
	g_aPunctuation[0x2044] = PUNCTUATION_FLAG_BASE;                                     // ⁄
	g_aPunctuation[0x2045] = PUNCTUATION_FLAG_BASE;                                     // ⁅
	g_aPunctuation[0x2046] = PUNCTUATION_FLAG_BASE;                                     // ⁆
	g_aPunctuation[0x2047] = PUNCTUATION_FLAG_BASE;                                     // ⁇
	g_aPunctuation[0x2048] = PUNCTUATION_FLAG_BASE;                                     // ⁈
	g_aPunctuation[0x2049] = PUNCTUATION_FLAG_BASE;                                     // ⁉
	g_aPunctuation[0x204A] = PUNCTUATION_FLAG_BASE;                                     // ⁊
	g_aPunctuation[0x204B] = PUNCTUATION_FLAG_BASE;                                     // ⁋
	g_aPunctuation[0x204C] = PUNCTUATION_FLAG_BASE;                                     // ⁌
	g_aPunctuation[0x204D] = PUNCTUATION_FLAG_BASE;                                     // ⁍
	g_aPunctuation[0x204E] = PUNCTUATION_FLAG_BASE;                                     // ⁎
	g_aPunctuation[0x204F] = PUNCTUATION_FLAG_BASE;                                     // ⁏
	g_aPunctuation[0x2050] = PUNCTUATION_FLAG_BASE;                                     // ⁐
	g_aPunctuation[0x2051] = PUNCTUATION_FLAG_BASE;                                     // ⁑
	g_aPunctuation[0x2052] = PUNCTUATION_FLAG_BASE;                                     // ⁒
	g_aPunctuation[0x2053] = PUNCTUATION_FLAG_BASE;                                     // ⁓
	g_aPunctuation[0x2054] = PUNCTUATION_FLAG_BASE;                                     // ⁔
	g_aPunctuation[0x2055] = PUNCTUATION_FLAG_BASE;                                     // ⁕
	g_aPunctuation[0x2056] = PUNCTUATION_FLAG_BASE;                                     // ⁖
	g_aPunctuation[0x2057] = PUNCTUATION_FLAG_BASE;                                     // ⁗
	g_aPunctuation[0x2058] = PUNCTUATION_FLAG_BASE;                                     // ⁘
	g_aPunctuation[0x2059] = PUNCTUATION_FLAG_BASE;                                     // ⁙
	g_aPunctuation[0x205A] = PUNCTUATION_FLAG_BASE;                                     // ⁚
	g_aPunctuation[0x205B] = PUNCTUATION_FLAG_BASE;                                     // ⁛
	g_aPunctuation[0x205C] = PUNCTUATION_FLAG_BASE;                                     // ⁜
	g_aPunctuation[0x205D] = PUNCTUATION_FLAG_BASE;                                     // ⁝
	g_aPunctuation[0x205E] = PUNCTUATION_FLAG_BASE;                                     // ⁞

	// Не смотря на то что следующий набор символов идет в блоке CJK Symbols and Punctuation
	// Word не считает их как EastAsian script (w:lang->w:eastAsian)

	g_aPunctuation[0x3001] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 、
	g_aPunctuation[0x3002] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 。
	g_aPunctuation[0x3003] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 〃
	g_aPunctuation[0x3004] = PUNCTUATION_FLAG_BASE;                                     // 〄
	g_aPunctuation[0x3005] = PUNCTUATION_FLAG_BASE;                                     // 々
	g_aPunctuation[0x3006] = PUNCTUATION_FLAG_BASE;                                     // 〆
	g_aPunctuation[0x3007] = PUNCTUATION_FLAG_BASE;                                     // 〇
	g_aPunctuation[0x3008] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 〈
	g_aPunctuation[0x3009] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 〉
	g_aPunctuation[0x300A] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 《
	g_aPunctuation[0x300B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 》
	g_aPunctuation[0x300C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 「
	g_aPunctuation[0x300D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 」
	g_aPunctuation[0x300E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 『
	g_aPunctuation[0x300F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 』
	g_aPunctuation[0x3010] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 【
	g_aPunctuation[0x3011] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 】
	g_aPunctuation[0x3012] = PUNCTUATION_FLAG_BASE;                                     // 〒
	g_aPunctuation[0x3013] = PUNCTUATION_FLAG_BASE;                                     // 〓
	g_aPunctuation[0x3014] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   //〔
	g_aPunctuation[0x3015] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 〕
	g_aPunctuation[0x3016] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   //〖
	g_aPunctuation[0x3017] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 〗
	g_aPunctuation[0x3018] = PUNCTUATION_FLAG_BASE;                                     // 〘
	g_aPunctuation[0x3019] = PUNCTUATION_FLAG_BASE;                                     // 〙
	g_aPunctuation[0x301A] = PUNCTUATION_FLAG_BASE;                                     // 〚
	g_aPunctuation[0x301B] = PUNCTUATION_FLAG_BASE;                                     // 〛
	g_aPunctuation[0x301C] = PUNCTUATION_FLAG_BASE;                                     // 〜
	g_aPunctuation[0x301D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_END;   // 〝
	g_aPunctuation[0x301E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // 〞
	g_aPunctuation[0x301F] = PUNCTUATION_FLAG_BASE;                                     // 〟

	g_aPunctuation[0xFF01] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ！
	g_aPunctuation[0xFF02] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ＂
	g_aPunctuation[0xFF03] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＃
	g_aPunctuation[0xFF04] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END;   // ＄
	g_aPunctuation[0xFF05] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ％
	g_aPunctuation[0xFF06] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＆
	g_aPunctuation[0xFF07] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ＇
	g_aPunctuation[0xFF08] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // （
	g_aPunctuation[0xFF09] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // )
	g_aPunctuation[0xFF0A] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＊
	g_aPunctuation[0xFF0B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＋
	g_aPunctuation[0xFF0C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ，
	g_aPunctuation[0xFF0D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // －
	g_aPunctuation[0xFF0E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ．
	g_aPunctuation[0xFF0F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ／
	g_aPunctuation[0xFF1A] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ：
	g_aPunctuation[0xFF1B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ；
	g_aPunctuation[0xFF1C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＜
	g_aPunctuation[0xFF1D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＝
	g_aPunctuation[0xFF1E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＞
	g_aPunctuation[0xFF1F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ？
	g_aPunctuation[0xFF20] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＠
	g_aPunctuation[0xFF3B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // ［
	g_aPunctuation[0xFF3C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＼
	g_aPunctuation[0xFF3D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ］
	g_aPunctuation[0xFF3E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＾
	g_aPunctuation[0xFF3F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ＿
	g_aPunctuation[0xFF40] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ｀
	g_aPunctuation[0xFF5B] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END | PUNCTUATION_FLAG_CANT_BE_AT_END_E;   // ｛
	g_aPunctuation[0xFF5C] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ｜
	g_aPunctuation[0xFF5D] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E; // ｝
	g_aPunctuation[0xFF5E] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ～
	g_aPunctuation[0xFF5F] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ｟
	g_aPunctuation[0xFF60] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ｠
	g_aPunctuation[0xFF61] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ｡
	g_aPunctuation[0xFF62] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ｢
	g_aPunctuation[0xFF63] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ｣
	g_aPunctuation[0xFF64] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ､
	g_aPunctuation[0xFF65] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ･
	g_aPunctuation[0xFFE0] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_BEGIN; // ￠
	g_aPunctuation[0xFFE1] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END;   // ￡
	g_aPunctuation[0xFFE2] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￢
	g_aPunctuation[0xFFE3] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￣
	g_aPunctuation[0xFFE4] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￤
	g_aPunctuation[0xFFE5] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN | PUNCTUATION_FLAG_CANT_BE_AT_END;   // ￥
	g_aPunctuation[0xFFE6] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￦
	g_aPunctuation[0xFFE8] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￨
	g_aPunctuation[0xFFE9] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￩
	g_aPunctuation[0xFFEA] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￪
	g_aPunctuation[0xFFEB] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￫
	g_aPunctuation[0xFFEC] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￬
	g_aPunctuation[0xFFED] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￭
	g_aPunctuation[0xFFEE] = PUNCTUATION_FLAG_BASE | PUNCTUATION_FLAG_EAST_ASIAN;                                     // ￮


	var offlineMode = '_offline_';
	var chartMode = '_chart_';
	
	var c_oSpecialPasteProps = {
		paste: 0,
		pasteOnlyFormula: 1,
		formulaNumberFormat: 2,
		formulaAllFormatting: 3,
		formulaWithoutBorders: 4, 
		formulaColumnWidth: 5,
		mergeConditionalFormating: 6, 
		pasteOnlyValues: 7,
		valueNumberFormat: 8,
		valueAllFormating: 9,
		pasteOnlyFormating: 10,
		transpose: 11,
		link: 12,
		picture: 13,
		linkedPicture: 14,

		sourceformatting: 15,
		destinationFormatting: 16,
		
		mergeFormatting: 17,

		uniteList: 18,
		doNotUniteList: 19,

		insertAsNestedTable: 20,
		uniteIntoTable: 21,
		insertAsNewRows: 22,
		keepTextOnly: 23,
		overwriteCells : 24
	};

	/** @enum {number} */
	var c_oAscNumberingFormat = {
		None        : 0x0000,
		Bullet      : 0x1001,
		Decimal     : 0x2002,
		LowerRoman  : 0x2003,
		UpperRoman  : 0x2004,
		LowerLetter : 0x2005,
		UpperLetter : 0x2006,
		DecimalZero : 0x2007,


		BulletFlag   : 0x1000,
		NumberedFlag : 0x2000
	};

	/** enum {number} */
	var c_oAscNumberingSuff = {
		Tab   : 0x01,
		Space : 0x02,
		None  : 0x03
	};

	var c_oAscNumberingLvlTextType = {
		Text : 0x00,
		Num  : 0x01
	};

	var c_oAscSdtAppearance = {
		Frame  : 1,
		Hidden : 2
	};

	//------------------------------------------------------------export--------------------------------------------------
	var prot;
	window['Asc']                          = window['Asc'] || {};
	window['Asc']['FONT_THUMBNAIL_HEIGHT'] = FONT_THUMBNAIL_HEIGHT;
	window['Asc']['c_oAscMaxColumnWidth']  = window['Asc'].c_oAscMaxColumnWidth = c_oAscMaxColumnWidth;
	window['Asc']['c_oAscMaxRowHeight'] = window['Asc'].c_oAscMaxRowHeight = c_oAscMaxRowHeight;
    window['Asc']['c_nMaxConversionTime'] = window['Asc'].c_nMaxConversionTime = c_nMaxConversionTime;
	window['Asc']['c_nMaxDownloadTitleLen'] = window['Asc'].c_nMaxDownloadTitleLen = c_nMaxDownloadTitleLen;
	window['Asc']['c_nVersionNoBase64'] = window['Asc'].c_nVersionNoBase64 = c_nVersionNoBase64;
	window['Asc']['c_dMaxParaRunContentLength'] = window['Asc'].c_dMaxParaRunContentLength = c_dMaxParaRunContentLength;
	window['Asc']['c_rUneditableTypes'] = window['Asc'].c_rUneditableTypes = c_rUneditableTypes;
	window['Asc']['c_oAscFileType'] = window['Asc'].c_oAscFileType = c_oAscFileType;
	prot                         = c_oAscFileType;
	prot['UNKNOWN']              = prot.UNKNOWN;
	prot['PDF']                  = prot.PDF;
	prot['PDFA']                 = prot.PDFA;
	prot['HTML']                 = prot.HTML;
	prot['DOCX']                 = prot.DOCX;
	prot['DOC']                  = prot.DOC;
	prot['ODT']                  = prot.ODT;
	prot['RTF']                  = prot.RTF;
	prot['TXT']                  = prot.TXT;
	prot['MHT']                  = prot.MHT;
	prot['EPUB']                 = prot.EPUB;
	prot['FB2']                  = prot.FB2;
	prot['MOBI']                 = prot.MOBI;
	prot['DOCY']                 = prot.DOCY;
	prot['JSON']                 = prot.JSON;
	prot['XLSX']                 = prot.XLSX;
	prot['XLS']                  = prot.XLS;
	prot['ODS']                  = prot.ODS;
	prot['CSV']                  = prot.CSV;
	prot['XLSY']                 = prot.XLSY;
	prot['PPTX']                 = prot.PPTX;
	prot['PPT']                  = prot.PPT;
	prot['ODP']                  = prot.ODP;
	window['Asc']['c_oAscError'] = window['Asc'].c_oAscError = c_oAscError;
	prot                                     = c_oAscError;
	prot['Level']                            = prot.Level;
	prot['ID']                               = prot.ID;
	prot                                     = c_oAscError.Level;
	prot['Critical']                         = prot.Critical;
	prot['NoCritical']                       = prot.NoCritical;
	prot                                     = c_oAscError.ID;
	prot['ServerSaveComplete']               = prot.ServerSaveComplete;
	prot['ConvertationProgress']             = prot.ConvertationProgress;
	prot['DownloadProgress']                 = prot.DownloadProgress;
	prot['No']                               = prot.No;
	prot['Unknown']                          = prot.Unknown;
	prot['ConvertationTimeout']              = prot.ConvertationTimeout;
	prot['DownloadError']                    = prot.DownloadError;
	prot['UnexpectedGuid']                   = prot.UnexpectedGuid;
	prot['Database']                         = prot.Database;
	prot['FileRequest']                      = prot.FileRequest;
	prot['FileVKey']                         = prot.FileVKey;
	prot['UplImageSize']                     = prot.UplImageSize;
	prot['UplImageExt']                      = prot.UplImageExt;
	prot['UplImageFileCount']                = prot.UplImageFileCount;
	prot['NoSupportClipdoard']               = prot.NoSupportClipdoard;
	prot['UplImageUrl']                      = prot.UplImageUrl;
	prot['MaxDataPointsError']               = prot.MaxDataPointsError;
	prot['StockChartError']                  = prot.StockChartError;
	prot['CoAuthoringDisconnect']            = prot.CoAuthoringDisconnect;
	prot['ConvertationPassword']             = prot.ConvertationPassword;
	prot['VKeyEncrypt']                      = prot.VKeyEncrypt;
	prot['KeyExpire']                        = prot.KeyExpire;
	prot['UserCountExceed']                  = prot.UserCountExceed;
	prot['AccessDeny']                       = prot.AccessDeny;
	prot['LoadingScriptError']               = prot.LoadingScriptError;
	prot['SplitCellMaxRows']                 = prot.SplitCellMaxRows;
	prot['SplitCellMaxCols']                 = prot.SplitCellMaxCols;
	prot['SplitCellRowsDivider']             = prot.SplitCellRowsDivider;
	prot['MobileUnexpectedCharCount']        = prot.MobileUnexpectedCharCount;
	prot['MailMergeLoadFile']                = prot.MailMergeLoadFile;
	prot['MailMergeSaveFile']                = prot.MailMergeSaveFile;
	prot['AutoFilterDataRangeError']         = prot.AutoFilterDataRangeError;
	prot['AutoFilterChangeFormatTableError'] = prot.AutoFilterChangeFormatTableError;
	prot['AutoFilterChangeError']            = prot.AutoFilterChangeError;
	prot['AutoFilterMoveToHiddenRangeError'] = prot.AutoFilterMoveToHiddenRangeError;
	prot['LockedAllError']                   = prot.LockedAllError;
	prot['LockedWorksheetRename']            = prot.LockedWorksheetRename;
	prot['FTChangeTableRangeError']          = prot.FTChangeTableRangeError;
	prot['FTRangeIncludedOtherTables']       = prot.FTRangeIncludedOtherTables;
	prot['PasteMaxRangeError']               = prot.PasteMaxRangeError;
	prot['PastInMergeAreaError']             = prot.PastInMergeAreaError;
	prot['CopyMultiselectAreaError']         = prot.CopyMultiselectAreaError;
	prot['DataRangeError']                   = prot.DataRangeError;
	prot['CannotMoveRange']                  = prot.CannotMoveRange;
	prot['MaxDataSeriesError']               = prot.MaxDataSeriesError;
	prot['CannotFillRange']                  = prot.CannotFillRange;
	prot['ConvertationOpenError']            = prot.ConvertationOpenError;
	prot['ConvertationSaveError']            = prot.ConvertationSaveError;
	prot['UserDrop']                         = prot.UserDrop;
	prot['Warning']                          = prot.Warning;
	prot['PrintMaxPagesCount']               = prot.PrintMaxPagesCount;
	prot['SessionAbsolute']                  = prot.SessionAbsolute;
	prot['SessionIdle']                      = prot.SessionIdle;
	prot['SessionToken']                     = prot.SessionToken;
	prot['FrmlWrongCountParentheses']        = prot.FrmlWrongCountParentheses;
	prot['FrmlWrongOperator']                = prot.FrmlWrongOperator;
	prot['FrmlWrongMaxArgument']             = prot.FrmlWrongMaxArgument;
	prot['FrmlWrongCountArgument']           = prot.FrmlWrongCountArgument;
	prot['FrmlWrongFunctionName']            = prot.FrmlWrongFunctionName;
	prot['FrmlAnotherParsingError']          = prot.FrmlAnotherParsingError;
	prot['FrmlWrongArgumentRange']           = prot.FrmlWrongArgumentRange;
	prot['FrmlOperandExpected']              = prot.FrmlOperandExpected;
	prot['FrmlParenthesesCorrectCount']      = prot.FrmlParenthesesCorrectCount;
	prot['FrmlWrongReferences']              = prot.FrmlWrongReferences;
	prot['InvalidReferenceOrName']           = prot.InvalidReferenceOrName;
	prot['LockCreateDefName']                = prot.LockCreateDefName;
	prot['LockedCellPivot']                  = prot.LockedCellPivot;
	prot['ForceSaveButton']                  = prot.ForceSaveButton;
	prot['ForceSaveTimeout']                 = prot.ForceSaveTimeout;
	prot['OpenWarning']                      = prot.OpenWarning;
	prot['DataEncrypted']                    = prot.DataEncrypted;
	window['Asc']['c_oAscAsyncAction']       = window['Asc'].c_oAscAsyncAction = c_oAscAsyncAction;
	prot                                     = c_oAscAsyncAction;
	prot['Open']                             = prot.Open;
	prot['Save']                             = prot.Save;
	prot['LoadDocumentFonts']                = prot.LoadDocumentFonts;
	prot['LoadDocumentImages']               = prot.LoadDocumentImages;
	prot['LoadFont']                         = prot.LoadFont;
	prot['LoadImage']                        = prot.LoadImage;
	prot['DownloadAs']                       = prot.DownloadAs;
	prot['Print']                            = prot.Print;
	prot['UploadImage']                      = prot.UploadImage;
	prot['ApplyChanges']                     = prot.ApplyChanges;
	prot['SlowOperation']                    = prot.SlowOperation;
	prot['LoadTheme']                        = prot.LoadTheme;
	prot['MailMergeLoadFile']                = prot.MailMergeLoadFile;
	prot['DownloadMerge']                    = prot.DownloadMerge;
	prot['SendMailMerge']                    = prot.SendMailMerge;
	prot['ForceSaveButton']                  = prot.ForceSaveButton;
	prot['ForceSaveTimeout']                 = prot.ForceSaveTimeout;
	window['Asc']['c_oAscAdvancedOptionsID'] = window['Asc'].c_oAscAdvancedOptionsID = c_oAscAdvancedOptionsID;
	prot                                         = c_oAscAdvancedOptionsID;
	prot['CSV']                                  = prot.CSV;
	prot['TXT']                                  = prot.TXT;
	prot['DRM']                                  = prot.DRM;
	window['Asc']['c_oAscFontRenderingModeType'] = window['Asc'].c_oAscFontRenderingModeType = c_oAscFontRenderingModeType;
	prot                                   = c_oAscFontRenderingModeType;
	prot['noHinting']                      = prot.noHinting;
	prot['hinting']                        = prot.hinting;
	prot['hintingAndSubpixeling']          = prot.hintingAndSubpixeling;
	window['Asc']['c_oAscAsyncActionType'] = window['Asc'].c_oAscAsyncActionType = c_oAscAsyncActionType;
	prot                                 = c_oAscAsyncActionType;
	prot['Information']                  = prot.Information;
	prot['BlockInteraction']             = prot.BlockInteraction;
	window['Asc']['c_oAscNumFormatType'] = window['Asc'].c_oAscNumFormatType = c_oAscNumFormatType;
	prot                                     = c_oAscNumFormatType;
	prot['None']                             = prot.None;
	prot['General']                          = prot.General;
	prot['Number']                           = prot.Number;
	prot['Scientific']                       = prot.Scientific;
	prot['Accounting']                       = prot.Accounting;
	prot['Currency']                         = prot.Currency;
	prot['Date']                             = prot.Date;
	prot['Time']                             = prot.Time;
	prot['Percent']                          = prot.Percent;
	prot['Fraction']                         = prot.Fraction;
	prot['Text']                             = prot.Text;
	prot['Custom']                           = prot.Custom;
	window['Asc']['c_oAscDrawingLayerType']  = c_oAscDrawingLayerType;
	prot                                     = c_oAscDrawingLayerType;
	prot['BringToFront']                     = prot.BringToFront;
	prot['SendToBack']                       = prot.SendToBack;
	prot['BringForward']                     = prot.BringForward;
	prot['SendBackward']                     = prot.SendBackward;
	window['Asc']['c_oAscTypeSelectElement'] = window['Asc'].c_oAscTypeSelectElement = c_oAscTypeSelectElement;
	prot                              = c_oAscTypeSelectElement;
	prot['Paragraph']                 = prot.Paragraph;
	prot['Table']                     = prot.Table;
	prot['Image']                     = prot.Image;
	prot['Header']                    = prot.Header;
	prot['Hyperlink']                 = prot.Hyperlink;
	prot['SpellCheck']                = prot.SpellCheck;
	prot['Shape']                     = prot.Shape;
	prot['Slide']                     = prot.Slide;
	prot['Chart']                     = prot.Chart;
	prot['Math']                      = prot.Math;
	prot['MailMerge']                 = prot.MailMerge;
	window['Asc']['linerule_AtLeast'] = window['Asc'].linerule_AtLeast = linerule_AtLeast;
	window['Asc']['linerule_Auto'] = window['Asc'].linerule_Auto = linerule_Auto;
	window['Asc']['linerule_Exact'] = window['Asc'].linerule_Exact = linerule_Exact;
	window['Asc']['c_oAscShdClear'] = window['Asc'].c_oAscShdClear = c_oAscShdClear;
	window['Asc']['c_oAscShdNil'] = window['Asc'].c_oAscShdNil = c_oAscShdNil;
	window['Asc']['c_oAscDropCap'] = window['Asc'].c_oAscDropCap = c_oAscDropCap;
	prot                                          = c_oAscDropCap;
	prot['None']                                  = prot.None;
	prot['Drop']                                  = prot.Drop;
	prot['Margin']                                = prot.Margin;
	window['Asc']['c_oAscChartTitleShowSettings'] = window['Asc'].c_oAscChartTitleShowSettings = c_oAscChartTitleShowSettings;
	prot                                                 = c_oAscChartTitleShowSettings;
	prot['none']                                         = prot.none;
	prot['overlay']                                      = prot.overlay;
	prot['noOverlay']                                    = prot.noOverlay;
	window['Asc']['c_oAscChartHorAxisLabelShowSettings'] = window['Asc'].c_oAscChartHorAxisLabelShowSettings = c_oAscChartHorAxisLabelShowSettings;
	prot                                                  = c_oAscChartHorAxisLabelShowSettings;
	prot['none']                                          = prot.none;
	prot['noOverlay']                                     = prot.noOverlay;
	window['Asc']['c_oAscChartVertAxisLabelShowSettings'] = window['Asc'].c_oAscChartVertAxisLabelShowSettings = c_oAscChartVertAxisLabelShowSettings;
	prot                                           = c_oAscChartVertAxisLabelShowSettings;
	prot['none']                                   = prot.none;
	prot['rotated']                                = prot.rotated;
	prot['vertical']                               = prot.vertical;
	prot['horizontal']                             = prot.horizontal;
	window['Asc']['c_oAscChartLegendShowSettings'] = window['Asc'].c_oAscChartLegendShowSettings = c_oAscChartLegendShowSettings;
	prot                                      = c_oAscChartLegendShowSettings;
	prot['none']                              = prot.none;
	prot['left']                              = prot.left;
	prot['top']                               = prot.top;
	prot['right']                             = prot.right;
	prot['bottom']                            = prot.bottom;
	prot['leftOverlay']                       = prot.leftOverlay;
	prot['rightOverlay']                      = prot.rightOverlay;
	prot['layout']                            = prot.layout;
	prot['topRight']                          = prot.topRight;
	window['Asc']['c_oAscChartDataLabelsPos'] = window['Asc'].c_oAscChartDataLabelsPos = c_oAscChartDataLabelsPos;
	prot                                     = c_oAscChartDataLabelsPos;
	prot['none']                             = prot.none;
	prot['b']                                = prot.b;
	prot['bestFit']                          = prot.bestFit;
	prot['ctr']                              = prot.ctr;
	prot['inBase']                           = prot.inBase;
	prot['inEnd']                            = prot.inEnd;
	prot['l']                                = prot.l;
	prot['outEnd']                           = prot.outEnd;
	prot['r']                                = prot.r;
	prot['t']                                = prot.t;
	window['Asc']['c_oAscGridLinesSettings'] = window['Asc'].c_oAscGridLinesSettings = c_oAscGridLinesSettings;
	prot                                     = c_oAscGridLinesSettings;
	prot['none']                             = prot.none;
	prot['major']                            = prot.major;
	prot['minor']                            = prot.minor;
	prot['majorMinor']                       = prot.majorMinor;
	window['Asc']['c_oAscChartTypeSettings'] = window['Asc'].c_oAscChartTypeSettings = c_oAscChartTypeSettings;
	prot                               = c_oAscChartTypeSettings;
	prot['barNormal']                  = prot.barNormal;
	prot['barStacked']                 = prot.barStacked;
	prot['barStackedPer']              = prot.barStackedPer;
	prot['barNormal3d']                = prot.barNormal3d;
	prot['barStacked3d']               = prot.barStacked3d;
	prot['barStackedPer3d']            = prot.barStackedPer3d;
	prot['barNormal3dPerspective']     = prot.barNormal3dPerspective;
	prot['lineNormal']                 = prot.lineNormal;
	prot['lineStacked']                = prot.lineStacked;
	prot['lineStackedPer']             = prot.lineStackedPer;
	prot['lineNormalMarker']           = prot.lineNormalMarker;
	prot['lineStackedMarker']          = prot.lineStackedMarker;
	prot['lineStackedPerMarker']       = prot.lineStackedPerMarker;
	prot['line3d']                     = prot.line3d;
	prot['pie']                        = prot.pie;
	prot['pie3d']                      = prot.pie3d;
	prot['hBarNormal']                 = prot.hBarNormal;
	prot['hBarStacked']                = prot.hBarStacked;
	prot['hBarStackedPer']             = prot.hBarStackedPer;
	prot['hBarNormal3d']               = prot.hBarNormal3d;
	prot['hBarStacked3d']              = prot.hBarStacked3d;
	prot['hBarStackedPer3d']           = prot.hBarStackedPer3d;
	prot['areaNormal']                 = prot.areaNormal;
	prot['areaStacked']                = prot.areaStacked;
	prot['areaStackedPer']             = prot.areaStackedPer;
	prot['doughnut']                   = prot.doughnut;
	prot['stock']                      = prot.stock;
	prot['scatter']                    = prot.scatter;
	prot['scatterLine']                = prot.scatterLine;
	prot['scatterLineMarker']          = prot.scatterLineMarker;
	prot['scatterMarker']              = prot.scatterMarker;
	prot['scatterNone']                = prot.scatterNone;
	prot['scatterSmooth']              = prot.scatterSmooth;
	prot['scatterSmoothMarker']        = prot.scatterSmoothMarker;
	prot['unknown']                    = prot.unknown;
	window['Asc']['c_oAscValAxisRule'] = window['Asc'].c_oAscValAxisRule = c_oAscValAxisRule;
	prot                              = c_oAscValAxisRule;
	prot['auto']                      = prot.auto;
	prot['fixed']                     = prot.fixed;
	window['Asc']['c_oAscValAxUnits'] = window['Asc'].c_oAscValAxUnits = c_oAscValAxUnits;
	prot                            = c_oAscValAxUnits;
	prot['BILLIONS']                = prot.BILLIONS;
	prot['HUNDRED_MILLIONS']        = prot.HUNDRED_MILLIONS;
	prot['HUNDREDS']                = prot.HUNDREDS;
	prot['HUNDRED_THOUSANDS']       = prot.HUNDRED_THOUSANDS;
	prot['MILLIONS']                = prot.MILLIONS;
	prot['TEN_MILLIONS']            = prot.TEN_MILLIONS;
	prot['TEN_THOUSANDS']           = prot.TEN_THOUSANDS;
	prot['TRILLIONS']               = prot.TRILLIONS;
	prot['CUSTOM']                  = prot.CUSTOM;
	prot['THOUSANDS']               = prot.THOUSANDS;
	window['Asc']['c_oAscTickMark'] = window['Asc'].c_oAscTickMark = c_oAscTickMark;
	prot                                 = c_oAscTickMark;
	prot['TICK_MARK_CROSS']              = prot.TICK_MARK_CROSS;
	prot['TICK_MARK_IN']                 = prot.TICK_MARK_IN;
	prot['TICK_MARK_NONE']               = prot.TICK_MARK_NONE;
	prot['TICK_MARK_OUT']                = prot.TICK_MARK_OUT;
	window['Asc']['c_oAscTickLabelsPos'] = window['Asc'].c_oAscTickLabelsPos = c_oAscTickLabelsPos;
	prot                                = c_oAscTickLabelsPos;
	prot['TICK_LABEL_POSITION_HIGH']    = prot.TICK_LABEL_POSITION_HIGH;
	prot['TICK_LABEL_POSITION_LOW']     = prot.TICK_LABEL_POSITION_LOW;
	prot['TICK_LABEL_POSITION_NEXT_TO'] = prot.TICK_LABEL_POSITION_NEXT_TO;
	prot['TICK_LABEL_POSITION_NONE']    = prot.TICK_LABEL_POSITION_NONE;
	window['Asc']['c_oAscCrossesRule']  = window['Asc'].c_oAscCrossesRule = c_oAscCrossesRule;
	prot                                     = c_oAscCrossesRule;
	prot['auto']                             = prot.auto;
	prot['maxValue']                         = prot.maxValue;
	prot['value']                            = prot.value;
	prot['minValue']                         = prot.minValue;
	window['Asc']['c_oAscBetweenLabelsRule'] = window['Asc'].c_oAscBetweenLabelsRule = c_oAscBetweenLabelsRule;
	prot                                  = c_oAscBetweenLabelsRule;
	prot['auto']                          = prot.auto;
	prot['manual']                        = prot.manual;
	window['Asc']['c_oAscLabelsPosition'] = window['Asc'].c_oAscLabelsPosition = c_oAscLabelsPosition;
	prot                            = c_oAscLabelsPosition;
	prot['byDivisions']             = prot.byDivisions;
	prot['betweenDivisions']        = prot.betweenDivisions;
	window['Asc']['c_oAscAxisType'] = window['Asc'].c_oAscAxisType = c_oAscAxisType;
	prot                           = c_oAscAxisType;
	prot['auto']                   = prot.auto;
	prot['date']                   = prot.date;
	prot['text']                   = prot.text;
	prot['cat']                    = prot.cat;
	prot['val']                    = prot.val;
	window['Asc']['c_oAscHAnchor'] = window['Asc'].c_oAscHAnchor = c_oAscHAnchor;
	prot                          = c_oAscHAnchor;
	prot['Margin']                = prot.Margin;
	prot['Page']                  = prot.Page;
	prot['Text']                  = prot.Text;
	prot['PageInternal']          = prot.PageInternal;
	window['Asc']['c_oAscXAlign'] = window['Asc'].c_oAscXAlign = c_oAscXAlign;
	prot                          = c_oAscXAlign;
	prot['Center']                = prot.Center;
	prot['Inside']                = prot.Inside;
	prot['Left']                  = prot.Left;
	prot['Outside']               = prot.Outside;
	prot['Right']                 = prot.Right;
	window['Asc']['c_oAscYAlign'] = window['Asc'].c_oAscYAlign = c_oAscYAlign;
	prot                           = c_oAscYAlign;
	prot['Bottom']                 = prot.Bottom;
	prot['Center']                 = prot.Center;
	prot['Inline']                 = prot.Inline;
	prot['Inside']                 = prot.Inside;
	prot['Outside']                = prot.Outside;
	prot['Top']                    = prot.Top;
	window['Asc']['c_oAscVAnchor'] = window['Asc'].c_oAscVAnchor = c_oAscVAnchor;
	prot                                 = c_oAscVAnchor;
	prot['Margin']                       = prot.Margin;
	prot['Page']                         = prot.Page;
	prot['Text']                         = prot.Text;
	window['Asc']['c_oAscRelativeFromH'] = window['Asc'].c_oAscRelativeFromH = c_oAscRelativeFromH;
	prot                                 = c_oAscRelativeFromH;
	prot['Character']                    = prot.Character;
	prot['Column']                       = prot.Column;
	prot['InsideMargin']                 = prot.InsideMargin;
	prot['LeftMargin']                   = prot.LeftMargin;
	prot['Margin']                       = prot.Margin;
	prot['OutsideMargin']                = prot.OutsideMargin;
	prot['Page']                         = prot.Page;
	prot['RightMargin']                  = prot.RightMargin;
	window['Asc']['c_oAscRelativeFromV'] = window['Asc'].c_oAscRelativeFromV = c_oAscRelativeFromV;
	prot                                   = c_oAscRelativeFromV;
	prot['BottomMargin']                   = prot.BottomMargin;
	prot['InsideMargin']                   = prot.InsideMargin;
	prot['Line']                           = prot.Line;
	prot['Margin']                         = prot.Margin;
	prot['OutsideMargin']                  = prot.OutsideMargin;
	prot['Page']                           = prot.Page;
	prot['Paragraph']                      = prot.Paragraph;
	prot['TopMargin']                      = prot.TopMargin;
	window['Asc']['c_oAscBorderStyles'] = window['AscCommon'].c_oAscBorderStyles = c_oAscBorderStyles;
	prot                         = c_oAscBorderStyles;
	prot['None']                 = prot.None;
	prot['Double']               = prot.Double;
	prot['Hair']                 = prot.Hair;
	prot['DashDotDot']           = prot.DashDotDot;
	prot['DashDot']              = prot.DashDot;
	prot['Dotted']               = prot.Dotted;
	prot['Dashed']               = prot.Dashed;
	prot['Thin']                 = prot.Thin;
	prot['MediumDashDotDot']     = prot.MediumDashDotDot;
	prot['SlantDashDot']         = prot.SlantDashDot;
	prot['MediumDashDot']        = prot.MediumDashDot;
	prot['MediumDashed']         = prot.MediumDashed;
	prot['Medium']               = prot.Medium;
	prot['Thick']                = prot.Thick;
	window['Asc']['c_oAscPageOrientation'] = window['Asc'].c_oAscPageOrientation = c_oAscPageOrientation;
	prot                         = c_oAscPageOrientation;
	prot['PagePortrait']         = prot.PagePortrait;
	prot['PageLandscape']        = prot.PageLandscape;
	window['Asc']['c_oAscColor'] = window['Asc'].c_oAscColor = c_oAscColor;
	prot                        = c_oAscColor;
	prot['COLOR_TYPE_NONE']     = prot.COLOR_TYPE_NONE;
	prot['COLOR_TYPE_SRGB']     = prot.COLOR_TYPE_SRGB;
	prot['COLOR_TYPE_PRST']     = prot.COLOR_TYPE_PRST;
	prot['COLOR_TYPE_SCHEME']   = prot.COLOR_TYPE_SCHEME;
	prot['COLOR_TYPE_SYS']      = prot.COLOR_TYPE_SYS;
	window['Asc']['c_oAscFill'] = window['Asc'].c_oAscFill = c_oAscFill;
	prot                                = c_oAscFill;
	prot['FILL_TYPE_NONE']              = prot.FILL_TYPE_NONE;
	prot['FILL_TYPE_BLIP']              = prot.FILL_TYPE_BLIP;
	prot['FILL_TYPE_NOFILL']            = prot.FILL_TYPE_NOFILL;
	prot['FILL_TYPE_SOLID']             = prot.FILL_TYPE_SOLID;
	prot['FILL_TYPE_GRAD']              = prot.FILL_TYPE_GRAD;
	prot['FILL_TYPE_PATT']              = prot.FILL_TYPE_PATT;
	prot['FILL_TYPE_GRP']               = prot.FILL_TYPE_GRP;
	window['Asc']['c_oAscFillGradType'] = window['Asc'].c_oAscFillGradType = c_oAscFillGradType;
	prot                                = c_oAscFillGradType;
	prot['GRAD_LINEAR']                 = prot.GRAD_LINEAR;
	prot['GRAD_PATH']                   = prot.GRAD_PATH;
	window['Asc']['c_oAscFillBlipType'] = window['Asc'].c_oAscFillBlipType = c_oAscFillBlipType;
	prot                              = c_oAscFillBlipType;
	prot['STRETCH']                   = prot.STRETCH;
	prot['TILE']                      = prot.TILE;
	window['Asc']['c_oAscStrokeType'] = window['Asc'].c_oAscStrokeType = c_oAscStrokeType;
	prot                                     = c_oAscStrokeType;
	prot['STROKE_NONE']                      = prot.STROKE_NONE;
	prot['STROKE_COLOR']                     = prot.STROKE_COLOR;
	window['Asc']['c_oAscVAlign'] = window['Asc'].c_oAscVAlign = c_oAscVAlign;
	prot                          = c_oAscVAlign;
	prot['Bottom']                = prot.Bottom;
	prot['Center']                = prot.Center;
	prot['Dist']                  = prot.Dist;
	prot['Just']                  = prot.Just;
	prot['Top']                   = prot.Top;
	window['Asc']['c_oAscVertDrawingText']   = c_oAscVertDrawingText;
	prot                                     = c_oAscVertDrawingText;
	prot['normal']                           = prot.normal;
	prot['vert']                             = prot.vert;
	prot['vert270']                          = prot.vert270;
	window['Asc']['c_oAscLineJoinType']      = c_oAscLineJoinType;
	prot                                     = c_oAscLineJoinType;
	prot['Round']                            = prot.Round;
	prot['Bevel']                            = prot.Bevel;
	prot['Miter']                            = prot.Miter;
	window['Asc']['c_oAscLineCapType']       = c_oAscLineCapType;
	prot                                     = c_oAscLineCapType;
	prot['Flat']                             = prot.Flat;
	prot['Round']                            = prot.Round;
	prot['Square']                           = prot.Square;
	window['Asc']['c_oAscLineBeginType']     = c_oAscLineBeginType;
	prot                                     = c_oAscLineBeginType;
	prot['None']                             = prot.None;
	prot['Arrow']                            = prot.Arrow;
	prot['Diamond']                          = prot.Diamond;
	prot['Oval']                             = prot.Oval;
	prot['Stealth']                          = prot.Stealth;
	prot['Triangle']                         = prot.Triangle;
	window['Asc']['c_oAscLineBeginSize']     = c_oAscLineBeginSize;
	prot                                     = c_oAscLineBeginSize;
	prot['small_small']                      = prot.small_small;
	prot['small_mid']                        = prot.small_mid;
	prot['small_large']                      = prot.small_large;
	prot['mid_small']                        = prot.mid_small;
	prot['mid_mid']                          = prot.mid_mid;
	prot['mid_large']                        = prot.mid_large;
	prot['large_small']                      = prot.large_small;
	prot['large_mid']                        = prot.large_mid;
	prot['large_large']                      = prot.large_large;
	window['Asc']['c_oAscCellTextDirection'] = window['Asc'].c_oAscCellTextDirection = c_oAscCellTextDirection;
	prot                                 = c_oAscCellTextDirection;
	prot['LRTB']                         = prot.LRTB;
	prot['TBRL']                         = prot.TBRL;
	prot['BTLR']                         = prot.BTLR;
	window['Asc']['c_oAscDocumentUnits'] = window['Asc'].c_oAscDocumentUnits = c_oAscDocumentUnits;
	prot                                    = c_oAscDocumentUnits;
	prot['Millimeter']                      = prot.Millimeter;
	prot['Inch']                            = prot.Inch;
	prot['Point']                           = prot.Point;
	window['Asc']['c_oAscMaxTooltipLength'] = window['Asc'].c_oAscMaxTooltipLength = c_oAscMaxTooltipLength;
	window['Asc']['c_oAscMaxCellOrCommentLength'] = window['Asc'].c_oAscMaxCellOrCommentLength = c_oAscMaxCellOrCommentLength;
	window['Asc']['c_oAscSelectionType'] = window['Asc'].c_oAscSelectionType = c_oAscSelectionType;
	prot                                 = c_oAscSelectionType;
	prot['RangeCells']                   = prot.RangeCells;
	prot['RangeCol']                     = prot.RangeCol;
	prot['RangeRow']                     = prot.RangeRow;
	prot['RangeMax']                     = prot.RangeMax;
	prot['RangeImage']                   = prot.RangeImage;
	prot['RangeChart']                   = prot.RangeChart;
	prot['RangeShape']                   = prot.RangeShape;
	prot['RangeShapeText']               = prot.RangeShapeText;
	prot['RangeChartText']               = prot.RangeChartText;
	prot['RangeFrozen']                  = prot.RangeFrozen;
	window['Asc']['c_oAscInsertOptions'] = window['Asc'].c_oAscInsertOptions = c_oAscInsertOptions;
	prot                                 = c_oAscInsertOptions;
	prot['InsertCellsAndShiftRight']     = prot.InsertCellsAndShiftRight;
	prot['InsertCellsAndShiftDown']      = prot.InsertCellsAndShiftDown;
	prot['InsertColumns']                = prot.InsertColumns;
	prot['InsertRows']                   = prot.InsertRows;
	prot['InsertTableRowAbove']          = prot.InsertTableRowAbove;
	prot['InsertTableRowBelow']          = prot.InsertTableRowBelow;
	prot['InsertTableColLeft']           = prot.InsertTableColLeft;
	prot['InsertTableColRight']          = prot.InsertTableColRight;
	window['Asc']['c_oAscDeleteOptions'] = window['Asc'].c_oAscDeleteOptions = c_oAscDeleteOptions;
	prot                            = c_oAscDeleteOptions;
	prot['DeleteCellsAndShiftLeft'] = prot.DeleteCellsAndShiftLeft;
	prot['DeleteCellsAndShiftTop']  = prot.DeleteCellsAndShiftTop;
	prot['DeleteColumns']           = prot.DeleteColumns;
	prot['DeleteRows']              = prot.DeleteRows;
	prot['DeleteTable']             = prot.DeleteTable;

	window['Asc']['c_oDashType'] = window['Asc'].c_oDashType = c_oDashType;
	prot                  = c_oDashType;
	prot['dash']          = prot.dash;
	prot['dashDot']       = prot.dashDot;
	prot['dot']           = prot.dot;
	prot['lgDash']        = prot.lgDash;
	prot['lgDashDot']     = prot.lgDashDot;
	prot['lgDashDotDot']  = prot.lgDashDotDot;
	prot['solid']         = prot.solid;
	prot['sysDash']       = prot.sysDash;
	prot['sysDashDot']    = prot.sysDashDot;
	prot['sysDashDotDot'] = prot.sysDashDotDot;
	prot['sysDot']        = prot.sysDot;


    window['Asc']['c_oAscMathInterfaceType'] = window['Asc'].c_oAscMathInterfaceType = c_oAscMathInterfaceType;
    prot                  = c_oAscMathInterfaceType;
    prot['Common'] = prot.Common;
    prot['Fraction'] = prot.Fraction;
    prot['Script'] = prot.Script;
    prot['Radical'] = prot.Radical;
    prot['LargeOperator'] = prot.LargeOperator;
    prot['Delimiter'] = prot.Delimiter;
    prot['Function'] = prot.Function;
    prot['Accent'] = prot.Accent;
    prot['BorderBox'] = prot.BorderBox;
    prot['Bar'] = prot.Bar;
    prot['Box'] = prot.Box;
    prot['Limit'] = prot.Limit;
    prot['GroupChar'] = prot.GroupChar;
    prot['Matrix'] = prot.Matrix;
    prot['EqArray'] = prot.EqArray;
    prot['Phantom'] = prot.Phantom;



	prot = window['Asc']['c_oAscMathInterfaceBarPos'] = window['Asc'].c_oAscMathInterfaceBarPos = c_oAscMathInterfaceBarPos;
	prot['Top']    = c_oAscMathInterfaceBarPos.Top;
	prot['Bottom'] = c_oAscMathInterfaceBarPos.Bottom;

	prot = window['Asc']['c_oAscMathInterfaceScript'] = window['Asc'].c_oAscMathInterfaceScript = c_oAscMathInterfaceScript;
	prot['None']      = c_oAscMathInterfaceScript.None;
	prot['Sup']       = c_oAscMathInterfaceScript.Sup;
	prot['Sub']       = c_oAscMathInterfaceScript.Sub;
	prot['SubSup']    = c_oAscMathInterfaceScript.SubSup;
	prot['PreSubSup'] = c_oAscMathInterfaceScript.PreSubSup;

	prot = window['Asc']['c_oAscMathInterfaceFraction'] = window['Asc'].c_oAscMathInterfaceFraction = c_oAscMathInterfaceFraction;
	prot['None']   = c_oAscMathInterfaceFraction.Bar;
	prot['Skewed'] = c_oAscMathInterfaceFraction.Skewed;
	prot['Linear'] = c_oAscMathInterfaceFraction.Linear;
	prot['NoBar']  = c_oAscMathInterfaceFraction.NoBar;

	prot = window['Asc']['c_oAscMathInterfaceLimitPos'] = window['Asc'].c_oAscMathInterfaceLimitPos = c_oAscMathInterfaceLimitPos;
	prot['None']   = c_oAscMathInterfaceLimitPos.None;
	prot['Top']    = c_oAscMathInterfaceLimitPos.Top;
	prot['Bottom'] = c_oAscMathInterfaceLimitPos.Bottom;

	prot = window['Asc']['c_oAscMathInterfaceMatrixMatrixAlign'] = window['Asc'].c_oAscMathInterfaceMatrixMatrixAlign = c_oAscMathInterfaceMatrixMatrixAlign;
	prot['Top']    = c_oAscMathInterfaceMatrixMatrixAlign.Top;
	prot['Center'] = c_oAscMathInterfaceMatrixMatrixAlign.Center;
	prot['Bottom'] = c_oAscMathInterfaceMatrixMatrixAlign.Bottom;

	prot = window['Asc']['c_oAscMathInterfaceMatrixColumnAlign'] = window['Asc'].c_oAscMathInterfaceMatrixColumnAlign = c_oAscMathInterfaceMatrixColumnAlign;
	prot['Left']   = c_oAscMathInterfaceMatrixColumnAlign.Left;
	prot['Center'] = c_oAscMathInterfaceMatrixColumnAlign.Center;
	prot['Right']  = c_oAscMathInterfaceMatrixColumnAlign.Right;

	prot = window['Asc']['c_oAscMathInterfaceEqArrayAlign'] = window['Asc'].c_oAscMathInterfaceEqArrayAlign = c_oAscMathInterfaceEqArrayAlign;
	prot['Top']    = c_oAscMathInterfaceEqArrayAlign.Top;
	prot['Center'] = c_oAscMathInterfaceEqArrayAlign.Center;
	prot['Bottom'] = c_oAscMathInterfaceEqArrayAlign.Bottom;

	prot = window['Asc']['c_oAscMathInterfaceNaryLimitLocation'] = window['Asc'].c_oAscMathInterfaceNaryLimitLocation = c_oAscMathInterfaceNaryLimitLocation;
	prot['UndOvr'] = c_oAscMathInterfaceNaryLimitLocation.UndOvr;
	prot['SubSup'] = c_oAscMathInterfaceNaryLimitLocation.SubSup;

	prot = window['Asc']['c_oAscMathInterfaceGroupCharPos'] = window['Asc'].c_oAscMathInterfaceGroupCharPos = c_oAscMathInterfaceGroupCharPos;
	prot['None']   = c_oAscMathInterfaceGroupCharPos.None;
	prot['Top']    = c_oAscMathInterfaceGroupCharPos.Top;
	prot['Bottom'] = c_oAscMathInterfaceGroupCharPos.Bottom;

	prot = window['Asc']['c_oAscTabLeader'] = window['Asc'].c_oAscTabLeader = c_oAscTabLeader;
	prot["None"]       = c_oAscTabLeader.None;
	prot["Heavy"]      = c_oAscTabLeader.Heavy;
	prot["Dot"]        = c_oAscTabLeader.Dot;
	prot["Hyphen"]     = c_oAscTabLeader.Hyphen;
	prot["MiddleDot"]  = c_oAscTabLeader.MiddleDot;
	prot["Underscore"] = c_oAscTabLeader.Underscore;

	prot = window['Asc']['c_oAscRestrictionType'] = window['Asc'].c_oAscRestrictionType = c_oAscRestrictionType;
	prot['None']           = c_oAscRestrictionType.None;
	prot['OnlyForms']      = c_oAscRestrictionType.OnlyForms;
	prot['OnlyComments']   = c_oAscRestrictionType.OnlyComments;
	prot['OnlySignatures'] = c_oAscRestrictionType.OnlySignatures;
	prot['View']           = c_oAscRestrictionType.View;

    window['AscCommon']                             = window['AscCommon'] || {};
	window["AscCommon"].g_cCharDelimiter            = g_cCharDelimiter;
	window["AscCommon"].g_cGeneralFormat            = g_cGeneralFormat;
	window["AscCommon"].bDate1904                   = false;
	window["AscCommon"].c_oAscAdvancedOptionsAction = c_oAscAdvancedOptionsAction;
	window["AscCommon"].DownloadType                = DownloadType;
	window["AscCommon"].CellValueType               = CellValueType;
	window["AscCommon"].c_oAscCellAnchorType        = c_oAscCellAnchorType;
	window["AscCommon"].c_oAscChartDefines          = c_oAscChartDefines;
	window["AscCommon"].c_oAscStyleImage            = c_oAscStyleImage;
	window["AscCommon"].c_oAscLineDrawingRule       = c_oAscLineDrawingRule;
	window["AscCommon"].vertalign_Baseline          = vertalign_Baseline;
	window["AscCommon"].vertalign_SuperScript       = vertalign_SuperScript;
	window["AscCommon"].vertalign_SubScript         = vertalign_SubScript;
	window["AscCommon"].hdrftr_Header               = hdrftr_Header;
	window["AscCommon"].hdrftr_Footer               = hdrftr_Footer;
	window["AscCommon"].c_oAscSizeRelFromH          = c_oAscSizeRelFromH;
	window["AscCommon"].c_oAscSizeRelFromV          = c_oAscSizeRelFromV;
	window["AscCommon"].c_oAscWrapStyle             = c_oAscWrapStyle;
	window["AscCommon"].c_oAscBorderWidth           = c_oAscBorderWidth;
	window["AscCommon"].c_oAscBorderType            = c_oAscBorderType;
	window["AscCommon"].c_oAscLockTypes             = c_oAscLockTypes;
	window["AscCommon"].c_oAscFormatPainterState    = c_oAscFormatPainterState;
	window["AscCommon"].c_oAscSaveTypes             = c_oAscSaveTypes;
	window["AscCommon"].c_oAscChartType             = c_oAscChartType;
	window["AscCommon"].c_oAscChartSubType          = c_oAscChartSubType;
	window["AscCommon"].c_oAscCsvDelimiter          = c_oAscCsvDelimiter;
	window["AscCommon"].c_oAscUrlType               = c_oAscUrlType;
	window["AscCommon"].c_oAscMouseMoveDataTypes    = c_oAscMouseMoveDataTypes;
	window["AscCommon"].c_oAscPrintDefaultSettings  = c_oAscPrintDefaultSettings;
	window["AscCommon"].c_oZoomType                 = c_oZoomType;
	window["AscCommon"].c_oNotifyType               = c_oNotifyType;
	window["AscCommon"].c_oNotifyParentType         = c_oNotifyParentType;
	window["AscCommon"].c_oAscEncodings             = c_oAscEncodings;
	window["AscCommon"].c_oAscEncodingsMap          = c_oAscEncodingsMap;
	window["AscCommon"].c_oAscCodePageNone          = c_oAscCodePageNone;
	window["AscCommon"].c_oAscCodePageUtf7          = c_oAscCodePageUtf7;
	window["AscCommon"].c_oAscCodePageUtf8          = c_oAscCodePageUtf8;
	window["AscCommon"].c_oAscCodePageUtf16         = c_oAscCodePageUtf16;
	window["AscCommon"].c_oAscCodePageUtf16BE       = c_oAscCodePageUtf16BE;
	window["AscCommon"].c_oAscCodePageUtf32         = c_oAscCodePageUtf32;
	window["AscCommon"].c_oAscCodePageUtf32BE       = c_oAscCodePageUtf32BE;
	window["AscCommon"].c_oAscMaxFormulaLength      = c_oAscMaxFormulaLength;

	window["AscCommon"].locktype_None   = locktype_None;
	window["AscCommon"].locktype_Mine   = locktype_Mine;
	window["AscCommon"].locktype_Other  = locktype_Other;
	window["AscCommon"].locktype_Other2 = locktype_Other2;
	window["AscCommon"].locktype_Other3 = locktype_Other3;

	window["AscCommon"].changestype_None                      = changestype_None;
	window["AscCommon"].changestype_Paragraph_Content         = changestype_Paragraph_Content;
	window["AscCommon"].changestype_Paragraph_Properties      = changestype_Paragraph_Properties;
	window["AscCommon"].changestype_Paragraph_AddText         = changestype_Paragraph_AddText;
	window["AscCommon"].changestype_Document_Content          = changestype_Document_Content;
	window["AscCommon"].changestype_Document_Content_Add      = changestype_Document_Content_Add;
	window["AscCommon"].changestype_Document_SectPr           = changestype_Document_SectPr;
	window["AscCommon"].changestype_Document_Styles           = changestype_Document_Styles;
	window["AscCommon"].changestype_Table_Properties          = changestype_Table_Properties;
	window["AscCommon"].changestype_Table_RemoveCells         = changestype_Table_RemoveCells;
	window["AscCommon"].changestype_Image_Properties          = changestype_Image_Properties;
	window["AscCommon"].changestype_ContentControl_Remove     = changestype_ContentControl_Remove;
	window["AscCommon"].changestype_ContentControl_Properties = changestype_ContentControl_Properties;
	window["AscCommon"].changestype_ContentControl_Add        = changestype_ContentControl_Add;
	window["AscCommon"].changestype_HdrFtr                    = changestype_HdrFtr;
	window["AscCommon"].changestype_Remove                    = changestype_Remove;
	window["AscCommon"].changestype_Delete                    = changestype_Delete;
	window["AscCommon"].changestype_Drawing_Props             = changestype_Drawing_Props;
	window["AscCommon"].changestype_ColorScheme               = changestype_ColorScheme;
	window["AscCommon"].changestype_Text_Props                = changestype_Text_Props;
	window["AscCommon"].changestype_RemoveSlide               = changestype_RemoveSlide;
	window["AscCommon"].changestype_Theme                     = changestype_Theme;
	window["AscCommon"].changestype_SlideSize                 = changestype_SlideSize;
	window["AscCommon"].changestype_SlideBg                   = changestype_SlideBg;
	window["AscCommon"].changestype_SlideTiming               = changestype_SlideTiming;
	window["AscCommon"].changestype_MoveComment               = changestype_MoveComment;
	window["AscCommon"].changestype_AddComment                = changestype_AddComment;
	window["AscCommon"].changestype_Layout                    = changestype_Layout;
	window["AscCommon"].changestype_AddShape                  = changestype_AddShape;
	window["AscCommon"].changestype_AddShapes                 = changestype_AddShapes;
	window["AscCommon"].changestype_PresDefaultLang           = changestype_PresDefaultLang;
	window["AscCommon"].changestype_SlideHide                 = changestype_SlideHide;
	window["AscCommon"].changestype_2_InlineObjectMove        = changestype_2_InlineObjectMove;
	window["AscCommon"].changestype_2_HdrFtr                  = changestype_2_HdrFtr;
	window["AscCommon"].changestype_2_Comment                 = changestype_2_Comment;
	window["AscCommon"].changestype_2_Element_and_Type        = changestype_2_Element_and_Type;
	window["AscCommon"].changestype_2_ElementsArray_and_Type  = changestype_2_ElementsArray_and_Type;
	window["AscCommon"].changestype_2_AdditionalTypes         = changestype_2_AdditionalTypes;
	window["AscCommon"].changestype_2_Element_and_Type_Array  = changestype_2_Element_and_Type_Array;
	window["AscCommon"].contentchanges_Add                    = contentchanges_Add;
	window["AscCommon"].contentchanges_Remove                 = contentchanges_Remove;

	window["AscCommon"].PUNCTUATION_FLAG_BASE                 = PUNCTUATION_FLAG_BASE;
	window["AscCommon"].PUNCTUATION_FLAG_CANT_BE_AT_BEGIN     = PUNCTUATION_FLAG_CANT_BE_AT_BEGIN;
	window["AscCommon"].PUNCTUATION_FLAG_CANT_BE_AT_END       = PUNCTUATION_FLAG_CANT_BE_AT_END;
	window["AscCommon"].PUNCTUATION_FLAG_EAST_ASIAN           = PUNCTUATION_FLAG_EAST_ASIAN;
	window["AscCommon"].PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E   = PUNCTUATION_FLAG_CANT_BE_AT_BEGIN_E;
	window["AscCommon"].PUNCTUATION_FLAG_CANT_BE_AT_END_E     = PUNCTUATION_FLAG_CANT_BE_AT_END_E;
	window["AscCommon"].g_aPunctuation                        = g_aPunctuation;

	window["AscCommon"].offlineMode = offlineMode;
	window["AscCommon"].chartMode = chartMode;

	window['AscCommon']['align_Right'] = window['AscCommon'].align_Right = align_Right;
	window['AscCommon']['align_Left'] = window['AscCommon'].align_Left = align_Left;
	window['AscCommon']['align_Center'] = window['AscCommon'].align_Center = align_Center;
	window['AscCommon']['align_Justify'] = window['AscCommon'].align_Justify = align_Justify;
	
	window['Asc']['c_oSpecialPasteProps'] = window['Asc'].c_oSpecialPasteProps = c_oSpecialPasteProps;
	prot = c_oSpecialPasteProps;
	prot['paste'] = prot.paste;
	prot['pasteOnlyFormula'] = prot.pasteOnlyFormula;
	prot['formulaNumberFormat'] = prot.formulaNumberFormat;
	prot['formulaAllFormatting'] = prot.formulaAllFormatting;
	prot['formulaWithoutBorders'] = prot.formulaWithoutBorders;
	prot['formulaColumnWidth'] = prot.formulaColumnWidth;
	prot['mergeConditionalFormating'] = prot.mergeConditionalFormating;
	prot['pasteOnlyValues'] = prot.pasteOnlyValues;
	prot['valueNumberFormat'] = prot.valueNumberFormat;
	prot['valueAllFormating'] = prot.valueAllFormating;
	prot['pasteOnlyFormating'] = prot.pasteOnlyFormating;
	prot['transpose'] = prot.transpose;
	prot['link'] = prot.link;
	prot['picture'] = prot.picture;
	prot['linkedPicture'] = prot.linkedPicture;
	prot['sourceformatting'] = prot.sourceformatting;
	prot['destinationFormatting'] = prot.destinationFormatting;
	prot['mergeFormatting'] = prot.mergeFormatting;
	prot['uniteList'] = prot.uniteList;
	prot['doNotUniteList'] = prot.doNotUniteList;
	prot['keepTextOnly'] = prot.keepTextOnly;
	prot['insertAsNestedTable'] = prot.insertAsNestedTable;
	prot['overwriteCells'] = prot.overwriteCells;

	window['Asc']['c_oAscNumberingFormat'] = window['Asc'].c_oAscNumberingFormat = c_oAscNumberingFormat;
	prot = c_oAscNumberingFormat;
	prot['None']        = c_oAscNumberingFormat.None;
	prot['Bullet']      = c_oAscNumberingFormat.Bullet;
	prot['Decimal']     = c_oAscNumberingFormat.Decimal;
	prot['LowerRoman']  = c_oAscNumberingFormat.LowerRoman;
	prot['UpperRoman']  = c_oAscNumberingFormat.UpperRoman;
	prot['LowerLetter'] = c_oAscNumberingFormat.LowerLetter;
	prot['UpperLetter'] = c_oAscNumberingFormat.UpperLetter;
	prot['DecimalZero'] = c_oAscNumberingFormat.DecimalZero;

	window['Asc']['c_oAscNumberingSuff'] = window['Asc'].c_oAscNumberingSuff = c_oAscNumberingSuff;
	prot = c_oAscNumberingSuff;
	prot['Tab']   = c_oAscNumberingSuff.Tab;
	prot['Space'] = c_oAscNumberingSuff.Space;
	prot['None']  = c_oAscNumberingSuff.None;

	window['Asc']['c_oAscNumberingLvlTextType'] = window['Asc'].c_oAscNumberingLvlTextType = c_oAscNumberingLvlTextType;
	prot = c_oAscNumberingLvlTextType;
	prot['Text'] = c_oAscNumberingLvlTextType.Text;
	prot['Num']  = c_oAscNumberingLvlTextType.Num;

	prot = window['Asc']['c_oAscSdtAppearance'] = window['Asc'].c_oAscSdtAppearance = c_oAscSdtAppearance;
	prot['Frame']  = c_oAscSdtAppearance.Frame;
	prot['Hidden'] = c_oAscSdtAppearance.Hidden;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
  function(window, undefined) {
  /**
   * Класс user для совместного редактирования/просмотра документа
   * -----------------------------------------------------------------------------
   *
   * @constructor
   * @memberOf Asc
   */
  function asc_CUser(val) {
    this.id = null;					// уникальный id - пользователя
    this.idOriginal = null;	// уникальный id - пользователя
    this.userName = null;		// имя пользователя
    this.state = undefined;	// состояние (true - подключен, false - отключился)
    this.indexUser = -1;		// Индекс пользователя (фактически равно числу заходов в документ на сервере)
    this.color = null;			// цвет пользователя
    this.view = false;			// просмотр(true), редактор(false)

    this._setUser(val);
    return this;
  }

  asc_CUser.prototype._setUser = function(val) {
    if (val) {
      this.id = val['id'];
      this.idOriginal = val['idOriginal'];
      this.userName = val['username'];
      this.indexUser = val['indexUser'];
      this.color = window['AscCommon'].getUserColorById(this.idOriginal, this.userName, false, true);
      this.view = val['view'];
    }
  };
  asc_CUser.prototype.asc_getId = function() {
    return this.id;
  };
  asc_CUser.prototype.asc_getIdOriginal = function() {
    return this.idOriginal;
  };
  asc_CUser.prototype.asc_getUserName = function() {
    return this.userName;
  };
  asc_CUser.prototype.asc_getFirstName = function() {
    return this.firstName;
  };
  asc_CUser.prototype.asc_getLastName = function() {
    return this.lastName;
  };
  asc_CUser.prototype.asc_getState = function() {
    return this.state;
  };
  asc_CUser.prototype.asc_getColor = function() {
    return '#' + ('000000' + this.color.toString(16)).substr(-6);
  };
  asc_CUser.prototype.asc_getView = function() {
    return this.view;
  };
  asc_CUser.prototype.setId = function(val) {
    this.id = val;
  };
  asc_CUser.prototype.setUserName = function(val) {
    this.userName = val;
  };
  asc_CUser.prototype.setFirstName = function(val) {
    this.firstName = val;
  };
  asc_CUser.prototype.setLastName = function(val) {
    this.lastName = val;
  };
  asc_CUser.prototype.setState = function(val) {
    this.state = val;
  };

  var ConnectionState = {
    Reconnect: -1,	// reconnect state
    None: 0,	// not initialized
    WaitAuth: 1,	// waiting session id
    Authorized: 2,	// authorized
    ClosedCoAuth: 3,	// closed coauthoring
    ClosedAll: 4,	// closed all

    SaveChanges: 10,	    // save
    AskSaveChanges: 11		// ask save
  };

  var c_oEditorId = {
    Word:0,
    Spreadsheet:1,
    Presentation:2
  };

  var c_oCloseCode = {
    serverShutdown: 4001,
    sessionIdle: 4002,
    sessionAbsolute: 4003,
	accessDeny: 4004,
	jwtExpired: 4005,
	jwtError: 4006,
	drop: 4007
  };
  
	var c_oAscServerCommandErrors = {
		NoError: 0,
		DocumentIdError: 1,
		ParseError: 2,
		UnknownError: 3,
		NotModified: 4,
		UnknownCommand: 5,
		Token: 6,
		TokenExpire: 7
	};
	
	var c_oAscForceSaveTypes = {
		Command: 0,
		Button: 1,
		Timeout: 2
	};

  /*
   * Export
   * -----------------------------------------------------------------------------
   */
  var prot;
  window['AscCommon'] = window['AscCommon'] || {};
  window["AscCommon"].asc_CUser = asc_CUser;
  prot = asc_CUser.prototype;
  prot["asc_getId"] = prot.asc_getId;
  prot["asc_getIdOriginal"] = prot.asc_getIdOriginal;
  prot["asc_getUserName"] = prot.asc_getUserName;
  prot["asc_getState"] = prot.asc_getState;
  prot["asc_getColor"] = prot.asc_getColor;
  prot["asc_getView"] = prot.asc_getView;

  window["AscCommon"].ConnectionState = ConnectionState;
  window["AscCommon"].c_oEditorId = c_oEditorId;
  window["AscCommon"].c_oCloseCode = c_oCloseCode;
  window["AscCommon"].c_oAscServerCommandErrors = c_oAscServerCommandErrors;
  window["AscCommon"].c_oAscForceSaveTypes = c_oAscForceSaveTypes;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(function(window, undefined) {
  'use strict';

  var Asc = window['Asc'];
  var AscCommon = window['AscCommon'];

  var ConnectionState = AscCommon.ConnectionState;
  var c_oEditorId = AscCommon.c_oEditorId;
  var c_oCloseCode = AscCommon.c_oCloseCode;
  var c_oAscServerCommandErrors = AscCommon.c_oAscServerCommandErrors;
  var c_oAscForceSaveTypes = AscCommon.c_oAscForceSaveTypes;

  // Класс надстройка, для online и offline работы
  function CDocsCoApi(options) {
    this._CoAuthoringApi = new DocsCoApi();
    this._onlineWork = false;

    if (options) {
      this.onAuthParticipantsChanged = options.onAuthParticipantsChanged;
      this.onParticipantsChanged = options.onParticipantsChanged;
      this.onMessage = options.onMessage;
      this.onServerVersion = options.onServerVersion;
      this.onCursor =  options.onCursor;
      this.onMeta =  options.onMeta;
      this.onSession =  options.onSession;
      this.onExpiredToken =  options.onExpiredToken;
	  this.onForceSave =  options.onForceSave;
      this.onHasForgotten =  options.onHasForgotten;
      this.onLocksAcquired = options.onLocksAcquired;
      this.onLocksReleased = options.onLocksReleased;
      this.onLocksReleasedEnd = options.onLocksReleasedEnd; // ToDo переделать на массив release locks
      this.onDisconnect = options.onDisconnect;
      this.onWarning = options.onWarning;
      this.onFirstLoadChangesEnd = options.onFirstLoadChangesEnd;
      this.onConnectionStateChanged = options.onConnectionStateChanged;
      this.onSetIndexUser = options.onSetIndexUser;
      this.onSpellCheckInit = options.onSpellCheckInit;
      this.onSaveChanges = options.onSaveChanges;
      this.onStartCoAuthoring = options.onStartCoAuthoring;
      this.onEndCoAuthoring = options.onEndCoAuthoring;
      this.onUnSaveLock = options.onUnSaveLock;
      this.onRecalcLocks = options.onRecalcLocks;
      this.onDocumentOpen = options.onDocumentOpen;
      this.onFirstConnect = options.onFirstConnect;
      this.onLicense = options.onLicense;
      this.onLicenseChanged = options.onLicenseChanged;
    }
  }

  CDocsCoApi.prototype.init = function(user, docid, documentCallbackUrl, token, editorType, documentFormatSave, docInfo) {
    if (this._CoAuthoringApi && this._CoAuthoringApi.isRightURL()) {
      var t = this;
      this._CoAuthoringApi.onAuthParticipantsChanged = function(e, id) {
        t.callback_OnAuthParticipantsChanged(e, id);
      };
      this._CoAuthoringApi.onParticipantsChanged = function(e) {
        t.callback_OnParticipantsChanged(e);
      };
      this._CoAuthoringApi.onMessage = function(e, clear) {
        t.callback_OnMessage(e, clear);
      };
      this._CoAuthoringApi.onServerVersion = function(e) {
      	t.callback_OnServerVersion(e);
	  };
      this._CoAuthoringApi.onCursor = function(e) {
        t.callback_OnCursor(e);
      };
      this._CoAuthoringApi.onMeta = function(e) {
        t.callback_OnMeta(e);
      };
      this._CoAuthoringApi.onSession = function(e) {
        t.callback_OnSession(e);
      };
      this._CoAuthoringApi.onExpiredToken = function(e) {
        t.callback_OnExpiredToken(e);
      };
      this._CoAuthoringApi.onHasForgotten = function(e) {
        t.callback_OnHasForgotten(e);
      };
	  this._CoAuthoringApi.onForceSave = function(e) {
        t.callback_OnForceSave(e);
      };
      this._CoAuthoringApi.onLocksAcquired = function(e) {
        t.callback_OnLocksAcquired(e);
      };
      this._CoAuthoringApi.onLocksReleased = function(e, bChanges) {
        t.callback_OnLocksReleased(e, bChanges);
      };
      this._CoAuthoringApi.onLocksReleasedEnd = function() {
        t.callback_OnLocksReleasedEnd();
      };
      this._CoAuthoringApi.onDisconnect = function(e, error) {
        t.callback_OnDisconnect(e, error);
      };
      this._CoAuthoringApi.onWarning = function(e) {
        t.callback_OnWarning(e);
      };
      this._CoAuthoringApi.onFirstLoadChangesEnd = function() {
        t.callback_OnFirstLoadChangesEnd();
      };
      this._CoAuthoringApi.onConnectionStateChanged = function(e) {
        t.callback_OnConnectionStateChanged(e);
      };
      this._CoAuthoringApi.onSetIndexUser = function(e) {
        t.callback_OnSetIndexUser(e);
      };
      this._CoAuthoringApi.onSpellCheckInit = function(e) {
        t.callback_OnSpellCheckInit(e);
      };
      this._CoAuthoringApi.onSaveChanges = function(e, userId, bFirstLoad) {
        t.callback_OnSaveChanges(e, userId, bFirstLoad);
      };
      // Callback есть пользователей больше 1
      this._CoAuthoringApi.onStartCoAuthoring = function(e) {
        t.callback_OnStartCoAuthoring(e);
      };
      this._CoAuthoringApi.onEndCoAuthoring = function(e) {
        t.callback_OnEndCoAuthoring(e);
      };
      this._CoAuthoringApi.onUnSaveLock = function() {
        t.callback_OnUnSaveLock();
      };
      this._CoAuthoringApi.onRecalcLocks = function(e) {
        t.callback_OnRecalcLocks(e);
      };
      this._CoAuthoringApi.onDocumentOpen = function(data) {
        t.callback_OnDocumentOpen(data);
      };
      this._CoAuthoringApi.onFirstConnect = function() {
        t.callback_OnFirstConnect();
      };
      this._CoAuthoringApi.onLicense = function(res) {
        t.callback_OnLicense(res);
      };
      this._CoAuthoringApi.onLicenseChanged = function(res) {
        t.callback_OnLicenseChanged(res);
	  };

      this._CoAuthoringApi.init(user, docid, documentCallbackUrl, token, editorType, documentFormatSave, docInfo);
      this._onlineWork = true;
    } else {
      // Фиктивные вызовы
      this.onFirstConnect();
      this.onLicense(null);
    }
  };

  CDocsCoApi.prototype.getDocId = function() {
    if (this._CoAuthoringApi) {
      return this._CoAuthoringApi.getDocId()
    }
    return undefined;
  };
  CDocsCoApi.prototype.setDocId = function(docId) {
    if (this._CoAuthoringApi) {
      return this._CoAuthoringApi.setDocId(docId)
    }
  };

  CDocsCoApi.prototype.auth = function(isViewer, opt_openCmd, opt_isIdle) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.auth(isViewer, opt_openCmd, opt_isIdle);
    } else {
      // Фиктивные вызовы
      this.callback_OnSpellCheckInit('');
      this.callback_OnSetIndexUser('123');
      this.onFirstLoadChangesEnd();
    }
  };

  CDocsCoApi.prototype.set_url = function(url) {
    if (this._CoAuthoringApi) {
      this._CoAuthoringApi.set_url(url);
    }
  };

  CDocsCoApi.prototype.get_onlineWork = function() {
    return this._onlineWork;
  };

  CDocsCoApi.prototype.get_state = function() {
    if (this._CoAuthoringApi) {
      return this._CoAuthoringApi.get_state();
    }

    return 0;
  };

  CDocsCoApi.prototype.openDocument = function(data) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.openDocument(data);
    }
  };

  CDocsCoApi.prototype.sendRawData = function(data) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.sendRawData(data);
    }
  };

  CDocsCoApi.prototype.getMessages = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.getMessages();
    }
  };

  CDocsCoApi.prototype.sendMessage = function(message) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.sendMessage(message);
    }
  };

  CDocsCoApi.prototype.sendCursor = function(cursor) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.sendCursor(cursor);
    }
  };

  CDocsCoApi.prototype.sendChangesError = function(data) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.sendChangesError(data);
    }
  };

  CDocsCoApi.prototype.askLock = function(arrayBlockId, callback) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.askLock(arrayBlockId, callback);
    } else {
      var t = this;
      window.setTimeout(function() {
        if (callback) {
          var lengthArray = (arrayBlockId) ? arrayBlockId.length : 0;
          if (0 < lengthArray) {
            callback({"lock": arrayBlockId[0]});
            // Фиктивные вызовы
            for (var i = 0; i < lengthArray; ++i) {
              t.callback_OnLocksAcquired({"state": 2, "block": arrayBlockId[i]});
            }
          }
        }
      }, 1);
    }
  };

  CDocsCoApi.prototype.askSaveChanges = function(callback) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.askSaveChanges(callback);
    } else {
      window.setTimeout(function() {
        if (callback) {
          // Фиктивные вызовы
          callback({"saveLock": false});
        }
      }, 100);
    }
  };

  CDocsCoApi.prototype.unSaveLock = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.unSaveLock();
    } else {
      var t = this;
      window.setTimeout(function() {
        // Фиктивные вызовы
        t.callback_OnUnSaveLock();
      }, 100);
    }
  };

  CDocsCoApi.prototype.saveChanges = function(arrayChanges, deleteIndex, excelAdditionalInfo, canUnlockDocument, canReleaseLocks) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.canUnlockDocument = canUnlockDocument;
      this._CoAuthoringApi.canReleaseLocks = canReleaseLocks;
      this._CoAuthoringApi.saveChanges(arrayChanges, null, deleteIndex, excelAdditionalInfo);
    }
  };

  CDocsCoApi.prototype.unLockDocument = function(isSave, canUnlockDocument, deleteIndex, canReleaseLocks) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.canUnlockDocument = canUnlockDocument;
      this._CoAuthoringApi.canReleaseLocks = canReleaseLocks;
      this._CoAuthoringApi.unLockDocument(isSave, deleteIndex);
    }
  };

  CDocsCoApi.prototype.getUsers = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.getUsers();
    }
  };

  CDocsCoApi.prototype.getUserConnectionId = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      return this._CoAuthoringApi.getUserConnectionId();
    }
    return null;
  };
  
  CDocsCoApi.prototype.get_indexUser = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      return this._CoAuthoringApi.get_indexUser();
    }
    return null;
  };

  CDocsCoApi.prototype.get_isAuth = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      return this._CoAuthoringApi.get_isAuth();
    }
    return null;
  };
  
  CDocsCoApi.prototype.get_jwt = function() {
    if (this._CoAuthoringApi && this._onlineWork) {
      return this._CoAuthoringApi.get_jwt();
    }
    return null;
  };

  CDocsCoApi.prototype.releaseLocks = function(blockId) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.releaseLocks(blockId);
    }
  };

  CDocsCoApi.prototype.disconnect = function(opt_code, opt_reason) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.disconnect(opt_code, opt_reason);
    }
  };

  CDocsCoApi.prototype.extendSession = function(idleTime) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.extendSession(idleTime);
    }
  };

  CDocsCoApi.prototype.versionHistory = function(data) {
    if (this._CoAuthoringApi && this._onlineWork) {
      this._CoAuthoringApi.versionHistory(data);
    }
  };

	CDocsCoApi.prototype.forceSave = function() {
		if (this._CoAuthoringApi && this._onlineWork) {
			return this._CoAuthoringApi.forceSave();
		}
		return false;
	};

  CDocsCoApi.prototype.callback_OnAuthParticipantsChanged = function(e, id) {
    if (this.onAuthParticipantsChanged) {
      this.onAuthParticipantsChanged(e, id);
    }
  };

  CDocsCoApi.prototype.callback_OnParticipantsChanged = function(e) {
    if (this.onParticipantsChanged) {
      this.onParticipantsChanged(e);
    }
  };

  CDocsCoApi.prototype.callback_OnMessage = function(e, clear) {
    if (this.onMessage) {
      this.onMessage(e, clear);
    }
  };

  CDocsCoApi.prototype.callback_OnServerVersion = function(e) {
  	if (this.onServerVersion) {
      this.onServerVersion(e);
	}
  };

  CDocsCoApi.prototype.callback_OnCursor = function(e) {
    if (this.onCursor) {
      this.onCursor(e);
    }
  };

  CDocsCoApi.prototype.callback_OnMeta = function(e) {
    if (this.onMeta) {
      this.onMeta(e);
    }
  };

  CDocsCoApi.prototype.callback_OnSession = function(e) {
    if (this.onSession) {
      this.onSession(e);
    }
  };

  CDocsCoApi.prototype.callback_OnExpiredToken = function(e) {
    if (this.onExpiredToken) {
      this.onExpiredToken(e);
    }
  };
  
  CDocsCoApi.prototype.callback_OnForceSave = function(e) {
    if (this.onForceSave) {
      this.onForceSave(e);
    }
  };

  CDocsCoApi.prototype.callback_OnHasForgotten = function(e) {
    if (this.onHasForgotten) {
      this.onHasForgotten(e);
    }
  };

  CDocsCoApi.prototype.callback_OnLocksAcquired = function(e) {
    if (this.onLocksAcquired) {
      this.onLocksAcquired(e);
    }
  };

  CDocsCoApi.prototype.callback_OnLocksReleased = function(e, bChanges) {
    if (this.onLocksReleased) {
      this.onLocksReleased(e, bChanges);
    }
  };

  CDocsCoApi.prototype.callback_OnLocksReleasedEnd = function() {
    if (this.onLocksReleasedEnd) {
      this.onLocksReleasedEnd();
    }
  };

  /**
   * Event об отсоединении от сервера
   * @param {jQuery} e  event об отсоединении с причиной
   * @param {code: Asc.c_oAscError.ID, level: Asc.c_oAscError.Level} error
   */
  CDocsCoApi.prototype.callback_OnDisconnect = function(e, error) {
    if (this.onDisconnect) {
      this.onDisconnect(e, error);
    }
  };

  CDocsCoApi.prototype.callback_OnWarning = function(e) {
    if (this.onWarning) {
      this.onWarning(e);
    }
  };

  CDocsCoApi.prototype.callback_OnFirstLoadChangesEnd = function() {
    if (this.onFirstLoadChangesEnd) {
      this.onFirstLoadChangesEnd();
    }
  };

  CDocsCoApi.prototype.callback_OnConnectionStateChanged = function(e) {
    if (this.onConnectionStateChanged) {
      this.onConnectionStateChanged(e);
    }
  };

  CDocsCoApi.prototype.callback_OnSetIndexUser = function(e) {
    if (this.onSetIndexUser) {
      this.onSetIndexUser(e);
    }
  };
  CDocsCoApi.prototype.callback_OnSpellCheckInit = function(e) {
    if (this.onSpellCheckInit) {
      this.onSpellCheckInit(e);
    }
  };

  CDocsCoApi.prototype.callback_OnSaveChanges = function(e, userId, bFirstLoad) {
    if (this.onSaveChanges) {
      this.onSaveChanges(e, userId, bFirstLoad);
    }
  };
  CDocsCoApi.prototype.callback_OnStartCoAuthoring = function(e) {
    if (this.onStartCoAuthoring) {
      this.onStartCoAuthoring(e);
    }
  };
  CDocsCoApi.prototype.callback_OnEndCoAuthoring = function(e) {
    if (this.onEndCoAuthoring) {
      this.onEndCoAuthoring(e);
    }
  };

  CDocsCoApi.prototype.callback_OnUnSaveLock = function() {
    if (this.onUnSaveLock) {
      this.onUnSaveLock();
    }
  };

  CDocsCoApi.prototype.callback_OnRecalcLocks = function(e) {
    if (this.onRecalcLocks) {
      this.onRecalcLocks(e);
    }
  };
  CDocsCoApi.prototype.callback_OnDocumentOpen = function(e) {
    if (this.onDocumentOpen) {
      this.onDocumentOpen(e);
    }
  };
  CDocsCoApi.prototype.callback_OnFirstConnect = function() {
    if (this.onFirstConnect) {
      this.onFirstConnect();
    }
  };
  CDocsCoApi.prototype.callback_OnLicense = function(res) {
    if (this.onLicense) {
      this.onLicense(res);
    }
  };
  CDocsCoApi.prototype.callback_OnLicenseChanged = function(res) {
    if (this.onLicenseChanged) {
      this.onLicenseChanged(res);
    }
  };

  function LockBufferElement(arrayBlockId, callback) {
    this._arrayBlockId = arrayBlockId ? arrayBlockId.slice() : null;
    this._callback = callback;
  }

  function DocsCoApi(options) {
    if (options) {
      this.onAuthParticipantsChanged = options.onAuthParticipantsChanged;
      this.onParticipantsChanged = options.onParticipantsChanged;
      this.onMessage = options.onMessage;
      this.onServerVersion = options.onServerVersion;
      this.onCursor = options.onCursor;
      this.onMeta = options.onMeta;
      this.onSession =  options.onSession;
      this.onExpiredToken =  options.onExpiredToken;
	  this.onForceSave =  options.onForceSave;
      this.onHasForgotten =  options.onHasForgotten;
      this.onLocksAcquired = options.onLocksAcquired;
      this.onLocksReleased = options.onLocksReleased;
      this.onLocksReleasedEnd = options.onLocksReleasedEnd; // ToDo переделать на массив release locks
      this.onRelockFailed = options.onRelockFailed;
      this.onDisconnect = options.onDisconnect;
      this.onWarning = options.onWarning;
      this.onSetIndexUser = options.onSetIndexUser;
      this.onSpellCheckInit = options.onSpellCheckInit;
      this.onSaveChanges = options.onSaveChanges;
      this.onFirstLoadChangesEnd = options.onFirstLoadChangesEnd;
      this.onConnectionStateChanged = options.onConnectionStateChanged;
      this.onUnSaveLock = options.onUnSaveLock;
      this.onRecalcLocks = options.onRecalcLocks;
      this.onDocumentOpen = options.onDocumentOpen;
      this.onFirstConnect = options.onFirstConnect;
      this.onLicense = options.onLicense;
      this.onLicenseChanged = options.onLicenseChanged;
    }
    this._state = ConnectionState.None;
    // Online-пользователи в документе
    this._participants = {};
    this._participantsTimestamp;
    this._countEditUsers = 0;
    this._countUsers = 0;

    this.isLicenseInit = false;
    this._locks = {};
    this._msgBuffer = [];
    this._msgInputBuffer = [];
    this._lockCallbacks = {};
    this._lockCallbacksErrorTimerId = {};
    this._saveCallback = [];
    this.saveLockCallbackErrorTimeOutId = null;
    this.saveCallbackErrorTimeOutId = null;
    this.unSaveLockCallbackErrorTimeOutId = null;
    this._id = null;
    this._sessionTimeConnect = null;
	this._allChangesSaved = null;
	this._lastForceSaveButtonTime = null;
	this._lastForceSaveTimeoutTime = null;
    this._indexUser = -1;
    // Если пользователей больше 1, то совместно редактируем
    this.isCoAuthoring = false;
    // Мы сами отключились от совместного редактирования
    this.isCloseCoAuthoring = false;

    // Максимальное число изменений, посылаемое на сервер (не может быть нечетным, т.к. пересчет обоих индексов должен быть)
    this.maxCountSaveChanges = 20000;
    // Текущий индекс для колличества изменений
    this.currentIndex = 0;
    // Индекс, с которого мы начинаем сохранять изменения
    this.deleteIndex = 0;
    // Массив изменений
    this.arrayChanges = null;
    // Время последнего сохранения (для разрыва соединения)
    this.lastOtherSaveTime = -1;
	this.lastOwnSaveTime = -1;
    // Локальный индекс изменений
    this.changesIndex = 0;
    // Дополнительная информация для Excel
    this.excelAdditionalInfo = null;
    // Unlock document
    this.canUnlockDocument = false;
    // Release locks
    this.canReleaseLocks = false;

    this._url = "";

    this.reconnectTimeout = null;
    this.attemptCount = 0;
    this.maxAttemptCount = 50;
    this.reconnectInterval = 2000;
    this.errorTimeOut = 10000;
    this.errorTimeOutSave = 60000;	// ToDo стоит переделать это, т.к. могут дублироваться изменения...

    this._docid = null;
    this._documentCallbackUrl = null;
    this._token = null;
    this._user = null;
    this._userId = "Anonymous";
    this.ownedLockBlocks = [];
    this.sockjs_url = null;
    this.sockjs = null;
    this.editorType = -1;
    this._isExcel = false;
    this._isPresentation = false;
    this._isAuth = false;
    this._documentFormatSave = 0;
    this.mode = undefined;
    this.permissions = undefined;
    this.lang = undefined;
    this.jwtOpen = undefined;
    this.jwtSession = undefined;
    this.encrypted = undefined;
    this._isViewer = false;
    this._isReSaveAfterAuth = false;	// Флаг для сохранения после повторной авторизации (для разрыва соединения во время сохранения)
    this._lockBuffer = [];
    this._authChanges = [];
    this._authOtherChanges = [];
  }

  DocsCoApi.prototype.isRightURL = function() {
    return ("" != this._url);
  };

  DocsCoApi.prototype.set_url = function(url) {
    this._url = url;
  };

  DocsCoApi.prototype.get_state = function() {
    return this._state;
  };

	DocsCoApi.prototype.check_state = function () {
		return ConnectionState.Authorized === this._state || ConnectionState.SaveChanges === this._state ||
			ConnectionState.AskSaveChanges === this._state;
	};

  DocsCoApi.prototype.get_indexUser = function() {
    return this._indexUser;
  };

  DocsCoApi.prototype.get_isAuth = function() {
    return this._isAuth;
  };

  DocsCoApi.prototype.get_jwt = function() {
    return this.jwtSession || this.jwtOpen;
  };

  DocsCoApi.prototype.getSessionId = function() {
    return this._id;
  };

  DocsCoApi.prototype.getUserConnectionId = function() {
    return this._userId;
  };

  DocsCoApi.prototype.getLocks = function() {
    return this._locks;
  };

  DocsCoApi.prototype._sendBufferedLocks = function() {
    var elem;
    for (var i = 0, length = this._lockBuffer.length; i < length; ++i) {
      elem = this._lockBuffer[i];
      this.askLock(elem._arrayBlockId, elem._callback);
    }
    this._lockBuffer = [];
  };

  DocsCoApi.prototype.askLock = function(arrayBlockId, callback) {
    if (ConnectionState.SaveChanges === this._state || ConnectionState.AskSaveChanges === this._state) {
      // Мы в режиме сохранения. Lock-и запросим после окончания.
      this._lockBuffer.push(new LockBufferElement(arrayBlockId, callback));
      return;
    }

    // ask all elements in array
    var t = this;
    var i = 0;
    var lengthArray = (arrayBlockId) ? arrayBlockId.length : 0;
    var isLock = false;
    var idLockInArray = null;
    for (; i < lengthArray; ++i) {
      idLockInArray = (this._isExcel || this._isPresentation) ? arrayBlockId[i]['guid'] : arrayBlockId[i];
      if (this._locks[idLockInArray] && 0 !== this._locks[idLockInArray].state) {
        isLock = true;
        break;
      }
    }
    if (0 === lengthArray) {
      isLock = true;
    }

    idLockInArray = (this._isExcel || this._isPresentation) ? arrayBlockId[0]['guid'] : arrayBlockId[0];

    if (!isLock) {
      if (this._lockCallbacksErrorTimerId.hasOwnProperty(idLockInArray)) {
        // Два раза для одного id нельзя запрашивать lock, не дождавшись ответа
        return;
      }
      //Ask
      this._locks[idLockInArray] = {'state': 1};//1-asked for block
      if (callback) {
        this._lockCallbacks[idLockInArray] = callback;

        //Set reconnectTimeout
        this._lockCallbacksErrorTimerId[idLockInArray] = window.setTimeout(function() {
          if (t._lockCallbacks.hasOwnProperty(idLockInArray)) {
            //Not signaled already
            t._lockCallbacks[idLockInArray]({error: 'Timed out'});
            delete t._lockCallbacks[idLockInArray];
            delete t._lockCallbacksErrorTimerId[idLockInArray];
          }
        }, this.errorTimeOut);
      }
      this._send({"type": 'getLock', 'block': arrayBlockId});
    } else {
      // Вернем ошибку, т.к. залочены элементы
      window.setTimeout(function() {
        if (callback) {
          callback({error: idLockInArray + '-lock'});
        }
      }, 100);
    }
  };

  DocsCoApi.prototype.askSaveChanges = function(callback) {
    if (this._saveCallback[this._saveCallback.length - 1]) {
      // Мы еще не отработали старый callback и ждем ответа
      return;
    }

    // Очищаем предыдущий таймер
    if (null !== this.saveLockCallbackErrorTimeOutId) {
      clearTimeout(this.saveLockCallbackErrorTimeOutId);
    }

    // Проверим состояние, если мы не подсоединились, то сразу отправим ошибку
    if (ConnectionState.Authorized !== this._state) {
      this.saveLockCallbackErrorTimeOutId = window.setTimeout(function() {
        if (callback) {
          // Фиктивные вызовы
          callback({error: "No connection"});
        }
      }, 100);
      return;
    }
    if (callback) {
      var t = this;
      var indexCallback = this._saveCallback.length;
      this._saveCallback[indexCallback] = callback;

      //Set reconnectTimeout
      this.saveLockCallbackErrorTimeOutId = window.setTimeout(function() {
        t.saveLockCallbackErrorTimeOutId = null;
        var oTmpCallback = t._saveCallback[indexCallback];
        if (oTmpCallback) {
          t._saveCallback[indexCallback] = null;
          //Not signaled already
          oTmpCallback({error: "Timed out"});
          t._state = ConnectionState.Authorized;
          // Делаем отложенные lock-и
          t._sendBufferedLocks();
        }
      }, this.errorTimeOut);
    }
    this._state = ConnectionState.AskSaveChanges;
    this._send({"type": "isSaveLock"});
  };

  DocsCoApi.prototype.unSaveLock = function() {
    // ToDo при разрыве соединения нужно перестать делать unSaveLock!
    var t = this;
    this.unSaveLockCallbackErrorTimeOutId = window.setTimeout(function() {
      t.unSaveLockCallbackErrorTimeOutId = null;
      t.unSaveLock();
    }, this.errorTimeOut);
    this._send({"type": "unSaveLock"});
  };

  DocsCoApi.prototype.releaseLocks = function(blockId) {
    if (this._locks[blockId] && 2 === this._locks[blockId].state /*lock is ours*/) {
      //Ask
      this._locks[blockId] = {"state": 0};//0-released
    }
  };

  DocsCoApi.prototype._reSaveChanges = function(reSaveType) {
    this.saveChanges(this.arrayChanges, this.currentIndex, undefined, undefined, reSaveType);
  };

  DocsCoApi.prototype.saveChanges = function(arrayChanges, currentIndex, deleteIndex, excelAdditionalInfo, reSave) {
    if (null === currentIndex) {
      this.deleteIndex = deleteIndex;
      if (null != this.deleteIndex && -1 !== this.deleteIndex) {
        this.deleteIndex += this.changesIndex;
      }
      this.currentIndex = 0;
      this.arrayChanges = arrayChanges;
      this.excelAdditionalInfo = excelAdditionalInfo;
    } else {
      this.currentIndex = currentIndex;
    }
    var startIndex = this.currentIndex * this.maxCountSaveChanges;
    var endIndex = Math.min(this.maxCountSaveChanges * (this.currentIndex + 1), arrayChanges.length);
    if (endIndex === arrayChanges.length) {
      for (var key in this._locks) if (this._locks.hasOwnProperty(key)) {
        if (2 === this._locks[key].state /*lock is ours*/) {
          delete this._locks[key];
        }
      }
    }

    //Set errorTimeout
    var t = this;
    this.saveCallbackErrorTimeOutId = window.setTimeout(function() {
      t.saveCallbackErrorTimeOutId = null;
      t._reSaveChanges(1);
    }, this.errorTimeOutSave);

    // Выставляем состояние сохранения
    this._state = ConnectionState.SaveChanges;

    this._send({'type': 'saveChanges', 'changes': JSON.stringify(arrayChanges.slice(startIndex, endIndex)),
      'startSaveChanges': (startIndex === 0), 'endSaveChanges': (endIndex === arrayChanges.length),
      'isCoAuthoring': this.isCoAuthoring, 'isExcel': this._isExcel, 'deleteIndex': this.deleteIndex,
      'excelAdditionalInfo': this.excelAdditionalInfo ? JSON.stringify(this.excelAdditionalInfo) : null,
        'unlock': this.canUnlockDocument, 'releaseLocks': this.canReleaseLocks, 'reSave': reSave});
  };

  DocsCoApi.prototype.unLockDocument = function(isSave, deleteIndex) {
    this.deleteIndex = deleteIndex;
    if (null != this.deleteIndex && -1 !== this.deleteIndex) {
      this.deleteIndex += this.changesIndex;
    }
    this._send({'type': 'unLockDocument', 'isSave': isSave, 'unlock': this.canUnlockDocument,
      'deleteIndex': this.deleteIndex, 'releaseLocks': this.canReleaseLocks});
  };

  DocsCoApi.prototype.getUsers = function() {
    // Специально для возможности получения после прохождения авторизации (Стоит переделать)
    if (this.onAuthParticipantsChanged) {
      this.onAuthParticipantsChanged(this._participants, this._userId);
    }
  };

  DocsCoApi.prototype.disconnect = function(opt_code, opt_reason) {
    // Отключаемся сами
    this.isCloseCoAuthoring = true;
    if (opt_code) {
      this.sockjs.close(opt_code, opt_reason);
    } else {
      this._send({"type": "close"});
      this._state = ConnectionState.ClosedCoAuth;
    }
  };

  DocsCoApi.prototype.extendSession = function(idleTime) {
    this._send({'type': 'extendSession', 'idletime': idleTime});
  };

  DocsCoApi.prototype.versionHistory = function(data) {
    this._send({'type': 'versionHistory', 'cmd': data});
  };

	DocsCoApi.prototype.forceSave = function() {
        var res = false;
		var newForceSaveButtonTime = Math.max(this.lastOtherSaveTime, this.lastOwnSaveTime);
		if (this._lastForceSaveButtonTime < newForceSaveButtonTime) {
			this._lastForceSaveButtonTime = newForceSaveButtonTime;
			this._send({'type': 'forceSaveStart'});
            res = true;
		}
		return res;
	};

  DocsCoApi.prototype.openDocument = function(data) {
    this._send({"type": "openDocument", "message": data});
  };

  DocsCoApi.prototype.sendRawData = function(data) {
    this._sendRaw(data);
  };

  DocsCoApi.prototype.getMessages = function() {
    this._send({"type": "getMessages"});
  };

  DocsCoApi.prototype.sendMessage = function(message) {
    if (typeof message === 'string') {
      this._send({"type": "message", "message": message});
    }
  };

  DocsCoApi.prototype.sendCursor = function(cursor) {
    if (typeof cursor === 'string') {
      this._send({"type": "cursor", "cursor": cursor});
    }
  };

  DocsCoApi.prototype.sendChangesError = function(data) {
    if (typeof data === 'string') {
      this._send({'type': 'changesError', 'stack': data});
    }
  };

  DocsCoApi.prototype._applyPrebuffered = function () {
    for (var i = 0; i < this._msgInputBuffer.length; ++i) {
      this._msgInputBuffer[i]();
    }
    this._msgInputBuffer = [];
  };
  DocsCoApi.prototype._sendPrebuffered = function() {
    for (var i = 0; i < this._msgBuffer.length; i++) {
      this._sendRaw(this._msgBuffer[i]);
    }
    this._msgBuffer = [];
  };

  DocsCoApi.prototype._send = function(data, useEncryption) {
    if (!useEncryption && data && data["type"] == "saveChanges" && AscCommon.EncryptionWorker && AscCommon.EncryptionWorker.isInit())
      return AscCommon.EncryptionWorker.sendChanges(this, data, AscCommon.EncryptionMessageType.Encrypt);

    if (data !== null && typeof data === "object") {
      if (this._state > 0) {
        this.sockjs.send(JSON.stringify(data));
      } else {
        this._msgBuffer.push(JSON.stringify(data));
      }
    }
  };

  DocsCoApi.prototype._sendRaw = function(data) {
    if (data !== null && typeof data === "string") {
      if (this._state > 0) {
        this.sockjs.send(data);
      } else {
        this._msgBuffer.push(data);
      }
    }
  };

  DocsCoApi.prototype._onMessages = function(data, clear) {
    if (this.check_state() && data["messages"] && this.onMessage) {
      this.onMessage(data["messages"], clear);
    }
  };

  DocsCoApi.prototype._onServerVersion = function (data) {
  	if (this.onServerVersion) {
		this.onServerVersion(data['buildVersion'], data['buildNumber']);
	}
  };

  DocsCoApi.prototype._onCursor = function(data) {
    if (this.check_state() && data["messages"] && this.onCursor) {
      this.onCursor(data["messages"]);
    }
  };

  DocsCoApi.prototype._onMeta = function(data) {
    if (data["messages"] && this.onMeta) {
      this.onMeta(data["messages"]);
    }
  };

  DocsCoApi.prototype._onSession = function(data) {
    if (this.check_state() && data["messages"] && this.onSession) {
      this.onSession(data["messages"]);
    }
  };

  DocsCoApi.prototype._onExpiredToken = function(data) {
    if (this.onExpiredToken) {
      this.onExpiredToken();
    }
  };

  DocsCoApi.prototype._onHasForgotten = function(data) {
    if (this.onHasForgotten) {
      this.onHasForgotten();
    }
  };

  DocsCoApi.prototype._onRefreshToken = function(jwt) {
    this.jwtOpen = undefined;
    if (jwt) {
      this.jwtSession = jwt;
    }
  };

	DocsCoApi.prototype._onForceSaveStart = function(data) {
	    var code = data['code'];
		if (code === c_oAscServerCommandErrors.NoError) {
			this._lastForceSaveButtonTime = data['time'];
            this.onForceSave({type: c_oAscForceSaveTypes.Button, start: true});
        } else if (code === c_oAscServerCommandErrors.NotModified) {
            this.onForceSave({type: c_oAscForceSaveTypes.Button, refuse: true});
		} else {
			this.onWarning(Asc.c_oAscError.ID.Unknown);
		}
	};
	DocsCoApi.prototype._onForceSave = function(data) {
        var type = data['type'];
		if (c_oAscForceSaveTypes.Button === type) {
			if (this._lastForceSaveButtonTime == data['time']) {
				this.onForceSave({type: type, success: data['success']});
			}
		} else {
			if (data['start']) {
                this.onForceSave({type: type, start: true});
				this._lastForceSaveTimeoutTime = data['time'];
			} else {
				if (this._lastForceSaveTimeoutTime == data['time']) {
					this.onForceSave({type: type, success: data['success']});
				}
			}
		}
	};

  DocsCoApi.prototype._onGetLock = function(data) {
    if (this.check_state() && data["locks"]) {
      for (var key in data["locks"]) {
        if (data["locks"].hasOwnProperty(key)) {
          var lock = data["locks"][key], blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : key, blockValue = (this._isExcel || this._isPresentation) ? lock["block"] : key;
          if (lock !== null) {
            var changed = true;
            if (this._locks[blockTmp] && 1 !== this._locks[blockTmp].state /*asked for it*/) {
              //Exists
              //Check lock state
              changed = !(this._locks[blockTmp].state === (lock["user"] === this._userId ? 2 : 3) && this._locks[blockTmp]["user"] === lock["user"] && this._locks[blockTmp]["time"] === lock["time"] && this._locks[blockTmp]["block"] === blockTmp);
            }

            if (changed) {
              this._locks[blockTmp] = {"state": lock["user"] === this._userId ? 2 : 3, "user": lock["user"], "time": lock["time"], "block": blockTmp, "blockValue": blockValue};//2-acquired by me!
            }
            if (this._lockCallbacks.hasOwnProperty(blockTmp)) {
              if (lock["user"] === this._userId) {
                //Do call back
                this._lockCallbacks[blockTmp]({"lock": this._locks[blockTmp]});
              } else {
                this._lockCallbacks[blockTmp]({"error": "Already locked by " + lock["user"]});
              }
              if (this._lockCallbacksErrorTimerId.hasOwnProperty(blockTmp)) {
                clearTimeout(this._lockCallbacksErrorTimerId[blockTmp]);
                delete this._lockCallbacksErrorTimerId[blockTmp];
              }
              delete this._lockCallbacks[blockTmp];
            }
            if (this.onLocksAcquired && changed) {
              this.onLocksAcquired(this._locks[blockTmp]);
            }
          }
        }
      }
    }
  };

  DocsCoApi.prototype._onReleaseLock = function(data) {
    if (this.check_state() && data["locks"]) {
      var bSendEnd = false;
      for (var block in data["locks"]) {
        if (data["locks"].hasOwnProperty(block)) {
          var lock = data["locks"][block], blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
          if (lock !== null) {
            this._locks[blockTmp] = {"state": 0, "user": lock["user"], "time": lock["time"], "changes": lock["changes"], "block": lock["block"]};
            if (this.onLocksReleased) {
              // false - user not save changes
              this.onLocksReleased(this._locks[blockTmp], false);
              bSendEnd = true;
            }
          }
        }
      }
      if (bSendEnd && this.onLocksReleasedEnd) {
        this.onLocksReleasedEnd();
      }
    }
  };

  DocsCoApi.prototype._documentOpen = function(data) {
    this.onDocumentOpen(data);
  };

  DocsCoApi.prototype._onSaveChanges = function(data, useEncryption) {
    if (!this.check_state()) {
      if (!this.get_isAuth()) {
        this._authOtherChanges.push(data);
      }
      return;
    }
    if (!useEncryption && AscCommon.EncryptionWorker && AscCommon.EncryptionWorker.isInit())
      return AscCommon.EncryptionWorker.sendChanges(this, data, AscCommon.EncryptionMessageType.Decrypt);
    if (data["locks"]) {
      var bSendEnd = false;
      for (var block in data["locks"]) {
        if (data["locks"].hasOwnProperty(block)) {
          var lock = data["locks"][block];
          if (lock !== null) {
            var blockTmp = (this._isExcel || this._isPresentation) ? lock["block"]["guid"] : lock["block"];
            this._locks[blockTmp] = {"state": 0, "user": lock["user"], "time": lock["time"], "changes": lock["changes"], "block": lock["block"]};
            if (this.onLocksReleased) {
              // true - lock with save
              this.onLocksReleased(this._locks[blockTmp], true);
              bSendEnd = true;
            }
          }
        }
      }
      if (bSendEnd && this.onLocksReleasedEnd) {
        this.onLocksReleasedEnd();
      }
    }
    this._updateChanges(data["changes"], data["changesIndex"], false);

    if (this.onRecalcLocks) {
      this.onRecalcLocks(data["excelAdditionalInfo"]);
    }
  };

  DocsCoApi.prototype._onStartCoAuthoring = function(isStartEvent, isWaitAuth) {
    if (false === this.isCoAuthoring) {
      this.isCoAuthoring = true;
      if (this.onStartCoAuthoring) {
        this.onStartCoAuthoring(isStartEvent);
      }
    } else if (isWaitAuth) {
      //it is a stub for unexpected situation(no direct reproduce scenery)
      //isCoAuthoring is true when more then one editor, but isWaitAuth mean than server has one editor
      this.canUnlockDocument = true;
      this.unLockDocument(false);
    }
  };

  DocsCoApi.prototype._onEndCoAuthoring = function(isStartEvent) {
    if (true === this.isCoAuthoring) {
      this.isCoAuthoring = false;
      if (this.onEndCoAuthoring) {
        this.onEndCoAuthoring(isStartEvent);
      }
    }
  };

	DocsCoApi.prototype._onSaveLock = function (data) {
		if (null != data["saveLock"]) {
			var indexCallback = this._saveCallback.length - 1;
			var oTmpCallback = this._saveCallback[indexCallback];
			if (oTmpCallback) {
				// Очищаем предыдущий таймер
				if (null !== this.saveLockCallbackErrorTimeOutId) {
					clearTimeout(this.saveLockCallbackErrorTimeOutId);
					this.saveLockCallbackErrorTimeOutId = null;
				}

				this._saveCallback[indexCallback] = null;
				oTmpCallback(data);
			}
		}
		if (null == data["saveLock"] || data['error'] || data["saveLock"]) {
			this._state = ConnectionState.Authorized;
			// Делаем отложенные lock-и
			this._sendBufferedLocks();
		}
	};

  DocsCoApi.prototype._onUnSaveLock = function(data) {
    // Очищаем предыдущий таймер сохранения
    if (null !== this.saveCallbackErrorTimeOutId) {
      clearTimeout(this.saveCallbackErrorTimeOutId);
      this.saveCallbackErrorTimeOutId = null;
    }
    // Очищаем предыдущий таймер снятия блокировки
    if (null !== this.unSaveLockCallbackErrorTimeOutId) {
      clearTimeout(this.unSaveLockCallbackErrorTimeOutId);
      this.unSaveLockCallbackErrorTimeOutId = null;
    }

    // Возвращаем состояние
    this._state = ConnectionState.Authorized;

    // Делаем отложенные lock-и
    this._sendBufferedLocks();

    if (-1 !== data['index']) {
      this.changesIndex = data['index'];
    }
	
    if (-1 !== data['time']) {
      this.lastOwnSaveTime = data['time'];
    }
	
    if (this.onUnSaveLock) {
      this.onUnSaveLock();
    }
  };

  DocsCoApi.prototype._updateChanges = function(allServerChanges, changesIndex, bFirstLoad) {
    if (this.onSaveChanges) {
      this.changesIndex = changesIndex;
      if (allServerChanges) {
        for (var i = 0; i < allServerChanges.length; ++i) {
          var change = allServerChanges[i];
          var changesOneUser = change['change'];
          if (changesOneUser) {
            if (change['user'] !== this._userId) {
              this.lastOtherSaveTime = change['time'];
            }
            this.onSaveChanges(JSON.parse(changesOneUser), change['useridoriginal'], bFirstLoad);
          }
        }
      }
    }
  };

  DocsCoApi.prototype._onSetIndexUser = function(data) {
    if (this.onSetIndexUser) {
      this.onSetIndexUser(data);
    }
  };
  DocsCoApi.prototype._onSpellCheckInit = function(data) {
    if (this.onSpellCheckInit) {
      this.onSpellCheckInit(data);
    }
  };

  DocsCoApi.prototype._onSavePartChanges = function(data) {
    // Очищаем предыдущий таймер
    if (null !== this.saveCallbackErrorTimeOutId) {
      clearTimeout(this.saveCallbackErrorTimeOutId);
      this.saveCallbackErrorTimeOutId = null;
    }

    if (-1 !== data['changesIndex']) {
      this.changesIndex = data['changesIndex'];
    }

    this.saveChanges(this.arrayChanges, this.currentIndex + 1);
  };

  DocsCoApi.prototype._onPreviousLocks = function(locks, previousLocks) {
    var i = 0;
    if (locks && previousLocks) {
      for (var block in locks) {
        if (locks.hasOwnProperty(block)) {
          var lock = locks[block];
          if (lock !== null && lock["block"]) {
            //Find in previous
            for (i = 0; i < previousLocks.length; i++) {
              if (previousLocks[i] === lock["block"] && lock["user"] === this._userId) {
                //Lock is ours
                previousLocks.remove(i);
                break;
              }
            }
          }
        }
      }
      if (previousLocks.length > 0 && this.onRelockFailed) {
        this.onRelockFailed(previousLocks);
      }
      previousLocks = [];
    }
  };

  DocsCoApi.prototype._onParticipantsChanged = function(participants, needChanged) {
    var participantsNew = {};
    var countEditUsersNew = 0;
    var countUsersNew = 0;
    var tmpUser;
    var i;
    var usersStateChanged = [];
    if (participants) {
      for (i = 0; i < participants.length; ++i) {
        tmpUser = new AscCommon.asc_CUser(participants[i]);
        participantsNew[tmpUser.asc_getId()] = tmpUser;
        if (!tmpUser.asc_getView()) {
          ++countEditUsersNew;
        }
        ++countUsersNew;
      }
    }
    if (needChanged) {
      for (i in participantsNew) {
        if (!this._participants[i]) {
          tmpUser = participantsNew[i];
          tmpUser.setState(true);
          usersStateChanged.push(tmpUser);
        }
      }
      for (i in this._participants) {
        if (!participantsNew[i]) {
          tmpUser = this._participants[i];
          tmpUser.setState(false);
          usersStateChanged.push(tmpUser);
        }
      }
    }
    this._participants = participantsNew;
    this._countEditUsers = countEditUsersNew;
    this._countUsers = countUsersNew;
    return usersStateChanged;
  };
  DocsCoApi.prototype._onAuthParticipantsChanged = function(participants) {
    this._participants = {};
    this._countEditUsers = 0;
    this._countUsers = 0;

    if (participants) {
      this._onParticipantsChanged(participants);

      if (this.onAuthParticipantsChanged) {
        this.onAuthParticipantsChanged(this._participants, this._userId);
      }

      // Посылаем эвент о совместном редактировании
      if (1 < this._countEditUsers) {
        this._onStartCoAuthoring(/*isStartEvent*/true);
      } else {
        this._onEndCoAuthoring(/*isStartEvent*/true);
      }
    }
  };

  DocsCoApi.prototype._onConnectionStateChanged = function(data) {
    var t = this;
    if (!this.check_state()) {
      this._msgInputBuffer.push(function () {
        t._onConnectionStateChanged(data);
      });
      return;
    }
    var isWaitAuth = data['waitAuth'];
    var usersStateChanged;
    if (this.onConnectionStateChanged && (!this._participantsTimestamp || this._participantsTimestamp <= data['participantsTimestamp'])) {
      this._participantsTimestamp = data['participantsTimestamp'];
      usersStateChanged = this._onParticipantsChanged(data['participants'], true);

      if (usersStateChanged.length > 0) {
        // Посылаем эвент о совместном редактировании
        if (1 < this._countEditUsers) {
          this._onStartCoAuthoring(/*isStartEvent*/false, isWaitAuth);
        } else {
          this._onEndCoAuthoring(/*isStartEvent*/false);
        }

        this.onParticipantsChanged(this._participants);
        for (var i = 0; i < usersStateChanged.length; ++i) {
          this.onConnectionStateChanged(usersStateChanged[i]);
        }
      }
    }
  };

  DocsCoApi.prototype._onLicenseChanged = function (data) {
    this.onLicenseChanged(data['licenseType']);
  };

  DocsCoApi.prototype._onDrop = function(data) {
    this.disconnect();
    this.onDisconnect(data ? data['description'] : '', this._getDisconnectErrorCode());
  };

  DocsCoApi.prototype._onWarning = function(data) {
    this.onWarning(Asc.c_oAscError.ID.Warning);
  };

  DocsCoApi.prototype._onLicense = function(data) {
    if (!this.isLicenseInit) {
      this.isLicenseInit = true;
      this.onLicense(data['license']);
    }
  };

  DocsCoApi.prototype._onAuth = function(data) {
    var t = this;
    this._onRefreshToken(data['jwt']);
    if (true === this._isAuth) {
      this._state = ConnectionState.Authorized;
      // Мы должны только соединиться для получения файла. Совместное редактирование уже было отключено.
      if (this.isCloseCoAuthoring) {
		  return;
	  }

	  this._onServerVersion(data);

      this._onLicenseChanged(data);
      // Мы уже авторизовывались, нужно обновить пользователей (т.к. пользователи могли входить и выходить пока у нас не было соединения)
      this._onAuthParticipantsChanged(data['participants']);

      //if (this.ownedLockBlocks && this.ownedLockBlocks.length > 0) {
      //	this._onPreviousLocks(data["locks"], this.ownedLockBlocks);
      //}
      this._onMessages(data, true);
      this._onGetLock(data);

      //Apply prebuffered
      this._applyPrebuffered();

      if (this._isReSaveAfterAuth) {
        this._isReSaveAfterAuth = false;
        var callbackAskSaveChanges = function(e) {
          if (false === e["saveLock"]) {
            t._reSaveChanges(2);
          } else {
            setTimeout(function() {
              t.askSaveChanges(callbackAskSaveChanges);
            }, 1000);
          }
        };
        this.askSaveChanges(callbackAskSaveChanges);
      }

      return;
    }
    if (data['result'] === 1) {
      // Выставляем флаг, что мы уже авторизовывались
      this._isAuth = true;

      //TODO: add checks
      this._state = ConnectionState.Authorized;
      this._id = data['sessionId'];
      this._indexUser = data['indexUser'];
      this._userId = this._user.asc_getId() + this._indexUser;
      this._sessionTimeConnect = data['sessionTimeConnect'];
      if (data['settings'] && data['settings']['reconnection']) {
        this.maxAttemptCount = data['settings']['reconnection']['attempts'];
        this.reconnectInterval = data['settings']['reconnection']['delay'];
      }

      this._onLicenseChanged(data);
      this._onAuthParticipantsChanged(data['participants']);

      this._onSpellCheckInit(data['g_cAscSpellCheckUrl']);
      this._onSetIndexUser(this._indexUser);

      this._onMessages(data, false);
      this._onGetLock(data);
      if (data['hasForgotten']) {
        this._onHasForgotten();
      }

      // Применения изменений пользователя
      if (window['AscApplyChanges'] && window['AscChanges']) {
        var userOfflineChanges = window['AscChanges'], changeOneUser;
        for (var i = 0; i < userOfflineChanges.length; ++i) {
          changeOneUser = userOfflineChanges[i];
          for (var j = 0; j < changeOneUser.length; ++j)
            this.onSaveChanges(changeOneUser[j], null, true);
        }
      }
      this._updateAuthChanges();
      // Посылать нужно всегда, т.к. на это рассчитываем при открытии
      if (this.onFirstLoadChangesEnd) {
        this.onFirstLoadChangesEnd();
      }

      //Apply prebuffered
      this._applyPrebuffered();

      //Send prebuffered
      this._sendPrebuffered();
    }
    //TODO: Add errors
  };
  DocsCoApi.prototype._onAuthChanges = function(data) {
    this._authChanges.push(data["changes"]);
  };
  DocsCoApi.prototype._updateAuthChanges = function() {
    //todo apply changes with chunk on arrival
    var changesIndex = 0, i, changes, data, indexDiff;
    for (i = 0; i < this._authChanges.length; ++i) {
      changes = this._authChanges[i];
      changesIndex += changes.length;
      this._updateChanges(changes, changesIndex, true);
    }
    this._authChanges = [];
    for (i = 0; i < this._authOtherChanges.length; ++i) {
      data = this._authOtherChanges[i];
      indexDiff = data["changesIndex"] - changesIndex;
      if (indexDiff > 0) {
        if (indexDiff >= data["changes"].length) {
          changes = data["changes"];
        } else {
          changes = data["changes"].splice(data["changes"].length - indexDiff, indexDiff);
        }
        changesIndex += changes.length;
        this._updateChanges(changes, changesIndex, true);
      }
    }
    this._authOtherChanges = [];
  };

  DocsCoApi.prototype.init = function(user, docid, documentCallbackUrl, token, editorType, documentFormatSave, docInfo) {
    this._user = user;
    this._docid = null;
    this._documentCallbackUrl = documentCallbackUrl;
    this._token = token;
    this.ownedLockBlocks = [];
    this.sockjs_url = null;
    this.editorType = editorType;
    this._isExcel = c_oEditorId.Spreadsheet === editorType;
    this._isPresentation = c_oEditorId.Presentation === editorType;
    this._isAuth = false;
    this._documentFormatSave = documentFormatSave;
	this.mode = docInfo.get_Mode();
	this.permissions = docInfo.get_Permissions();
	this.lang = docInfo.get_Lang();
	this.jwtOpen = docInfo.get_Token();
    this.encrypted = docInfo.get_Encrypted();

    this.setDocId(docid);
    this._initSocksJs();
  };
  DocsCoApi.prototype.getDocId = function() {
    return this._docid;
  };
  DocsCoApi.prototype.setDocId = function(docid) {
    //todo возможно надо менять sockjs_url
    this._docid = docid;
    this.sockjs_url = AscCommon.getBaseUrl() + '../../../../doc/' + docid + '/c';
  };
  // Авторизация (ее нужно делать после выставления состояния редактора view-mode)
  DocsCoApi.prototype.auth = function(isViewer, opt_openCmd, opt_isIdle) {
    this._isViewer = isViewer;
    if (this._locks) {
      this.ownedLockBlocks = [];
      //If we already have locks
      for (var block in this._locks) if (this._locks.hasOwnProperty(block)) {
        var lock = this._locks[block];
        if (lock["state"] === 2) {
          //Our lock.
          this.ownedLockBlocks.push(lock["blockValue"]);
        }
      }
      this._locks = {};
    }
    this._send({
      'type': 'auth',
      'docid': this._docid,
      'documentCallbackUrl': this._documentCallbackUrl,
      'token': this._token,
      'user': {
        'id': this._user.asc_getId(),
        'username': this._user.asc_getUserName(),
        'firstname': this._user.asc_getFirstName(),
        'lastname': this._user.asc_getLastName(),
        'indexUser': this._indexUser
      },
      'editorType': this.editorType,
      'lastOtherSaveTime': this.lastOtherSaveTime,
      'block': this.ownedLockBlocks,
      'sessionId': this._id,
	  'sessionTimeConnect': this._sessionTimeConnect,
      'sessionTimeIdle': opt_isIdle >= 0 ? opt_isIdle : 0,
      'documentFormatSave': this._documentFormatSave,
      'view': this._isViewer,
      'isCloseCoAuthoring': this.isCloseCoAuthoring,
      'openCmd': opt_openCmd,
      'lang': this.lang,
      'mode': this.mode,
      'permissions': this.permissions,
      'encrypted': this.encrypted,
      'jwtOpen': this.jwtOpen,
      'jwtSession': this.jwtSession
    });
  };

    DocsCoApi.prototype._initSocksJs = function () {
        var t = this;
        var sockjs;
        sockjs = this.sockjs = {};

        var send = function (data) {
            setTimeout(function () {
                sockjs.onmessage({
                    data: JSON.stringify(data)
                });
            });
        };
        var license = {
            type: 'license',
            license: {
                type: 3,
                mode: 0,
                //light: false,
                //trial: false,
                rights: 1,
                buildVersion: "5.2.6",
                buildNumber: 2,
                //branding: false
            }
        };

        var channel;

        require([
            '/common/outer/worker-channel.js',
            '/common/common-util.js'
        ], function (Channel, Util) {
            var msgEv = Util.mkEvent();
            var p = window.parent;
            window.addEventListener('message', function (msg) {
                if (msg.source !== p) { return; }
                msgEv.fire(msg);
            });
            var postMsg = function (data) {
                p.postMessage(data, '*');
            };
            Channel.create(msgEv, postMsg, function (chan) {
                channel = chan;
                send(license);

                chan.on('CMD', function (obj) {
                    send(obj);
                });
            });
        });

        sockjs.onopen = function() {
          t._state = ConnectionState.WaitAuth;
            t.onFirstConnect();
        };
        sockjs.onopen();

        sockjs.close = function () {
            console.error('Close realtime');
        };

        sockjs.send = function (data) {
            try {
                var obj = JSON.parse(data);
            } catch (e) {
                console.error(e);
                return;
            }
            if (channel) {
                channel.event('CMD', obj);
            }
        };

        sockjs.onmessage = function (e) {
            t._onServerMessage(e.data);
        };

        return sockjs;
    };

	DocsCoApi.prototype._onServerOpen = function () {
		if (this.reconnectTimeout) {
			clearTimeout(this.reconnectTimeout);
			this.reconnectTimeout = null;
			this.attemptCount = 0;
		}

		this._state = ConnectionState.WaitAuth;
		this.onFirstConnect();
	};
	DocsCoApi.prototype._onServerMessage = function (data) {
		//TODO: add checks and error handling
		//Get data type
		var dataObject = JSON.parse(data);
		switch (dataObject['type']) {
			case 'auth'        :
				this._onAuth(dataObject);
				break;
			case 'message'      :
				this._onMessages(dataObject, false);
				break;
			case 'cursor'       :
				this._onCursor(dataObject);
				break;
			case 'meta' :
				this._onMeta(dataObject);
				break;
			case 'getLock'      :
				this._onGetLock(dataObject);
				break;
			case 'releaseLock'    :
				this._onReleaseLock(dataObject);
				break;
			case 'connectState'    :
				this._onConnectionStateChanged(dataObject);
				break;
			case 'saveChanges'    :
				this._onSaveChanges(dataObject);
				break;
			case 'authChanges' :
				this._onAuthChanges(dataObject);
				break;
			case 'saveLock'      :
				this._onSaveLock(dataObject);
				break;
			case 'unSaveLock'    :
				this._onUnSaveLock(dataObject);
				break;
			case 'savePartChanges'  :
				this._onSavePartChanges(dataObject);
				break;
			case 'drop'        :
				this._onDrop(dataObject);
				break;
			case 'waitAuth'      : /*Ждем, когда придет auth, документ залочен*/
				break;
			case 'error'      : /*Старая версия sdk*/
				this._onDrop(dataObject);
				break;
			case 'documentOpen'    :
				this._documentOpen(dataObject);
				break;
			case 'warning':
				this._onWarning(dataObject);
				break;
			case 'license':
				this._onLicense(dataObject);
				break;
			case 'session' :
				this._onSession(dataObject);
				break;
			case 'refreshToken' :
				this._onRefreshToken(dataObject["messages"]);
				break;
			case 'expiredToken' :
				this._onExpiredToken();
				break;
			case 'forceSaveStart' :
				this._onForceSaveStart(dataObject["messages"]);
				break;
			case 'forceSave' :
				this._onForceSave(dataObject["messages"]);
				break;
		}
	};
	DocsCoApi.prototype._onServerClose = function (evt) {
		if (ConnectionState.SaveChanges === this._state) {
			// Мы сохраняли изменения и разорвалось соединение
			this._isReSaveAfterAuth = true;
			// Очищаем предыдущий таймер
			if (null !== this.saveCallbackErrorTimeOutId) {
				clearTimeout(this.saveCallbackErrorTimeOutId);
				this.saveCallbackErrorTimeOutId = null;
			}
		}
		this._state = ConnectionState.Reconnect;
		var bIsDisconnectAtAll = ((c_oCloseCode.serverShutdown <= evt.code && evt.code <= c_oCloseCode.drop) ||
			this.attemptCount >= this.maxAttemptCount);
		var error = null;
		if (bIsDisconnectAtAll) {
			this._state = ConnectionState.ClosedAll;
			error = this._getDisconnectErrorCode(evt.code);
		}
		if (this.onDisconnect) {
			this.onDisconnect(evt.reason, error);
		}
		//Try reconect
		if (!bIsDisconnectAtAll) {
			this._tryReconnect();
		}
	};
	DocsCoApi.prototype._reconnect = function () {
		delete this.sockjs;
		this._initSocksJs();
	};
	DocsCoApi.prototype._tryReconnect = function () {
		var t = this;
		if (this.reconnectTimeout) {
			clearTimeout(this.reconnectTimeout);
			t.reconnectTimeout = null;
		}
		++this.attemptCount;
		this.reconnectTimeout = setTimeout(function () {
			t._reconnect();
		}, this.reconnectInterval);
	};

	DocsCoApi.prototype._getDisconnectErrorCode = function(opt_closeCode) {
		var code = this.isCloseCoAuthoring ? Asc.c_oAscError.ID.UserDrop : Asc.c_oAscError.ID.CoAuthoringDisconnect;
		var level = Asc.c_oAscError.Level.NoCritical;
		if (c_oCloseCode.serverShutdown === opt_closeCode) {
			code = Asc.c_oAscError.ID.CoAuthoringDisconnect;
		} else if (c_oCloseCode.sessionIdle === opt_closeCode) {
			code = Asc.c_oAscError.ID.SessionIdle;
		} else if (c_oCloseCode.sessionAbsolute === opt_closeCode) {
			code = Asc.c_oAscError.ID.SessionAbsolute;
		} else if (c_oCloseCode.accessDeny === opt_closeCode) {
			code = Asc.c_oAscError.ID.AccessDeny;
		} else if (c_oCloseCode.jwtExpired === opt_closeCode) {
			if (this.jwtSession) {
				code = Asc.c_oAscError.ID.SessionToken;
			} else {
				code = Asc.c_oAscError.ID.KeyExpire;
				level = Asc.c_oAscError.Level.Critical;
			}
		} else if (c_oCloseCode.jwtError === opt_closeCode) {
			code = Asc.c_oAscError.ID.VKeyEncrypt;
			level = Asc.c_oAscError.Level.Critical;
		} else if (c_oCloseCode.drop === opt_closeCode) {
			code = Asc.c_oAscError.ID.UserDrop;
		}
		return {code: code, level: level};
	};

  //----------------------------------------------------------export----------------------------------------------------
  window['AscCommon'] = window['AscCommon'] || {};
  window['AscCommon'].CDocsCoApi = CDocsCoApi;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function (window, undefined) {

	var Asc = window['Asc'];
	var AscCommon = window['AscCommon'];

	// Import
	var prot;
	var c_oAscMouseMoveDataTypes = AscCommon.c_oAscMouseMoveDataTypes;

	var c_oAscColor = Asc.c_oAscColor;
	var c_oAscFill = Asc.c_oAscFill;
	var c_oAscFillBlipType = Asc.c_oAscFillBlipType;
	var c_oAscChartTypeSettings = Asc.c_oAscChartTypeSettings;
	var c_oAscTickMark = Asc.c_oAscTickMark;
	var c_oAscAxisType = Asc.c_oAscAxisType;
	// ---------------------------------------------------------------------------------------------------------------

	var c_oAscArrUserColors = [16757719, 7929702, 56805, 10081791, 12884479, 16751001, 6748927, 16762931, 6865407,
		15650047, 16737894, 3407768, 16759142, 10852863, 6750176, 16774656, 13926655, 13815039, 3397375, 11927347, 16752947,
		9404671, 4980531, 16744678, 3407830, 15919360, 16731553, 52479, 13330175, 16743219, 3386367, 14221056, 16737966,
		1896960, 65484, 10970879, 16759296, 16711680, 13496832, 62072, 49906, 16734720, 10682112, 7890687, 16731610, 65406,
		38655, 16747008, 59890, 12733951, 15859712, 47077, 15050496, 15224319, 10154496, 58807, 16724950, 1759488, 9981439,
		15064320, 15893248, 16724883, 58737, 15007744, 36594, 12772608, 12137471, 6442495, 15039488, 16718470, 14274816,
		53721, 16718545, 1625088, 15881472, 13419776, 32985, 16711800, 1490688, 16711884, 8991743, 13407488, 41932, 7978752,
		15028480, 52387, 15007927, 12114176, 1421824, 55726, 13041893, 10665728, 30924, 49049, 14241024, 36530, 11709440,
		13397504, 45710, 34214];

	function CreateAscColorCustom(r, g, b, auto) {
		var ret = new asc_CColor();
		ret.type = c_oAscColor.COLOR_TYPE_SRGB;
		ret.r = r;
		ret.g = g;
		ret.b = b;
		ret.a = 255;
		ret.Auto = ( undefined === auto ? false : auto );
		return ret;
	}

	function CreateAscColor(unicolor) {
      if (null == unicolor || null == unicolor.color) {
          return new asc_CColor();
      }

		var ret = new asc_CColor();
		ret.r = unicolor.RGBA.R;
		ret.g = unicolor.RGBA.G;
		ret.b = unicolor.RGBA.B;
		ret.a = unicolor.RGBA.A;

		var _color = unicolor.color;
		switch (_color.type) {
			case c_oAscColor.COLOR_TYPE_SRGB:
			case c_oAscColor.COLOR_TYPE_SYS: {
				break;
			}
			case c_oAscColor.COLOR_TYPE_PRST:
			case c_oAscColor.COLOR_TYPE_SCHEME: {
				ret.type = _color.type;
				ret.value = _color.id;
				break;
			}
			default:
				break;
		}
		return ret;
	}

	function CreateGUID()
	{
		function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);	}

		var val = '{' + s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4() + '}';
		val = val.toUpperCase();
		return val;
	}

	var c_oLicenseResult = {
		Error         : 1,
		Expired       : 2,
		Success       : 3,
		UnknownUser   : 4,
		Connections   : 5,
		ExpiredTrial  : 6,
		SuccessLimit  : 7,
		UsersCount    : 8,
		ConnectionsOS : 9,
		UsersCountOS  : 10
	};

	var c_oRights = {
		None    : 0,
		Edit    : 1,
		Review  : 2,
		Comment : 3,
		View    : 4
	};

	var c_oLicenseMode = {
		None: 0,
		Trial: 1,
		Developer: 2
	};

	var EPluginDataType = {
		none: "none",
		text: "text",
		ole: "ole",
		html: "html",
        desktop: "desktop"
	};

	/** @constructor */
	function asc_CSignatureLine()
	{
		this.id = undefined;
		this.guid = "";
		this.signer1 = "";
		this.signer2 = "";
		this.email = "";

		this.instructions = "";
		this.showDate = false;

		this.valid = 0;

		this.image = "";

		this.date = "";
		this.isvisible = false;
		this.isrequested = false;
	}
	asc_CSignatureLine.prototype.correct = function()
	{
		if (this.id == null)
			this.id = "0";
		if (this.guid == null)
			this.guid = "";
		if (this.signer1 == null)
			this.signer1 = "";
		if (this.signer2 == null)
			this.signer2 = "";
		if (this.email == null)
			this.email = "";
		if (this.instructions == null)
			this.instructions = "";
		if (this.showDate == null)
			this.showDate = false;
		if (this.valid == null)
			this.valid = 0;
		if (this.image == null)
			this.image = "";
		if (this.date == null)
			this.date = "";
		if (this.isvisible == null)
			this.isvisible = false;
	};
	asc_CSignatureLine.prototype.asc_getId = function(){ return this.id; };
	asc_CSignatureLine.prototype.asc_setId = function(v){ this.id = v; };
	asc_CSignatureLine.prototype.asc_getGuid = function(){ return this.guid; };
	asc_CSignatureLine.prototype.asc_setGuid = function(v){ this.guid = v; };
	asc_CSignatureLine.prototype.asc_getSigner1 = function(){ return this.signer1; };
	asc_CSignatureLine.prototype.asc_setSigner1 = function(v){ this.signer1 = v; };
	asc_CSignatureLine.prototype.asc_getSigner2 = function(){ return this.signer2; };
	asc_CSignatureLine.prototype.asc_setSigner2 = function(v){ this.signer2 = v; };
	asc_CSignatureLine.prototype.asc_getEmail = function(){ return this.email; };
	asc_CSignatureLine.prototype.asc_setEmail = function(v){ this.email = v; };
	asc_CSignatureLine.prototype.asc_getInstructions = function(){ return this.instructions; };
	asc_CSignatureLine.prototype.asc_setInstructions = function(v){ this.instructions = v; };
	asc_CSignatureLine.prototype.asc_getShowDate = function(){ return this.showDate; };
	asc_CSignatureLine.prototype.asc_setShowDate = function(v){ this.showDate = v; };
	asc_CSignatureLine.prototype.asc_getValid = function(){ return this.valid; };
	asc_CSignatureLine.prototype.asc_setValid = function(v){ this.valid = v; };
	asc_CSignatureLine.prototype.asc_getDate = function(){ return this.date; };
	asc_CSignatureLine.prototype.asc_setDate = function(v){ this.date = v; };
	asc_CSignatureLine.prototype.asc_getVisible = function(){ return this.isvisible; };
	asc_CSignatureLine.prototype.asc_setVisible = function(v){ this.isvisible = v; };
	asc_CSignatureLine.prototype.asc_getRequested = function(){ return this.isrequested; };
	asc_CSignatureLine.prototype.asc_setRequested = function(v){ this.isrequested = v; };

	/**
	 * Класс asc_CAscEditorPermissions для прав редакторов
	 * -----------------------------------------------------------------------------
	 *
	 * @constructor
	 * @memberOf Asc
	 */
	function asc_CAscEditorPermissions() {
		this.licenseType = c_oLicenseResult.Error;
		this.licenseMode = c_oLicenseMode.None;
		this.isLight = false;
		this.rights = c_oRights.None;

		this.canCoAuthoring = true;
		this.canReaderMode = true;
		this.canBranding = false;
		this.isAutosaveEnable = true;
		this.AutosaveMinInterval = 300;
		this.isAnalyticsEnable = false;
		this.buildVersion = null;
		this.buildNumber = null;
		return this;
	}

	asc_CAscEditorPermissions.prototype.asc_getLicenseType = function () {
		return this.licenseType;
	};
	asc_CAscEditorPermissions.prototype.asc_getCanCoAuthoring = function () {
		return this.canCoAuthoring;
	};
	asc_CAscEditorPermissions.prototype.asc_getCanReaderMode = function () {
		return this.canReaderMode;
	};
	asc_CAscEditorPermissions.prototype.asc_getCanBranding = function () {
		return this.canBranding;
	};
	asc_CAscEditorPermissions.prototype.asc_getIsAutosaveEnable = function () {
		return this.isAutosaveEnable;
	};
	asc_CAscEditorPermissions.prototype.asc_getAutosaveMinInterval = function () {
		return this.AutosaveMinInterval;
	};
	asc_CAscEditorPermissions.prototype.asc_getIsAnalyticsEnable = function () {
		return this.isAnalyticsEnable;
	};
	asc_CAscEditorPermissions.prototype.asc_getIsLight = function () {
		return this.isLight;
	};
	asc_CAscEditorPermissions.prototype.asc_getLicenseMode = function () {
		return this.licenseMode;
	};
	asc_CAscEditorPermissions.prototype.asc_getRights = function () {
		return this.rights;
	};
	asc_CAscEditorPermissions.prototype.asc_getBuildVersion = function () {
		return this.buildVersion;
	};
	asc_CAscEditorPermissions.prototype.asc_getBuildNumber = function () {
		return this.buildNumber;
	};

	asc_CAscEditorPermissions.prototype.setLicenseType = function (v) {
		this.licenseType = v;
	};
	asc_CAscEditorPermissions.prototype.setCanBranding = function (v) {
		this.canBranding = v;
	};
	asc_CAscEditorPermissions.prototype.setIsLight = function (v) {
		this.isLight = v;
	};
	asc_CAscEditorPermissions.prototype.setLicenseMode = function (v) {
		this.licenseMode = v;
	};
	asc_CAscEditorPermissions.prototype.setRights = function (v) {
		this.rights = v;
	};
	asc_CAscEditorPermissions.prototype.setBuildVersion = function (v) {
		this.buildVersion = v;
	};
	asc_CAscEditorPermissions.prototype.setBuildNumber = function (v) {
		this.buildNumber = v;
	};

	/** @constructor */
	function asc_ValAxisSettings() {
		this.minValRule = null;
		this.minVal = null;
		this.maxValRule = null;
		this.maxVal = null;
		this.invertValOrder = null;
		this.logScale = null;
		this.logBase = null;

		this.dispUnitsRule = null;
		this.units = null;


		this.showUnitsOnChart = null;
		this.majorTickMark = null;
		this.minorTickMark = null;
		this.tickLabelsPos = null;
		this.crossesRule = null;
		this.crosses = null;
		this.axisType = c_oAscAxisType.val;
	}

	asc_ValAxisSettings.prototype = {


		isEqual: function(oPr){
			if(!oPr){
				return false;
			}
            if(this.minValRule !== oPr.minValRule){
				return false;
			}
            if(this.minVal !== oPr.minVal){
            	return false;
			}
            if(this.maxValRule !== oPr.maxValRule){
            	return false;
			}
            if(this.maxVal !== oPr.maxVal){
            	return false;
			}
            if(this.invertValOrder !== oPr.invertValOrder){
            	return false;
			}
            if(this.logScale !== oPr.logScale){
            	return false;
			}
            if(this.logBase !== oPr.logBase){
            	return false;
			}
            if(this.dispUnitsRule !== oPr.dispUnitsRule){
            	return false;
			}
            if(this.units !== oPr.units){
            	return false;
			}
            if(this.showUnitsOnChart !== oPr.showUnitsOnChart){
            	return false;
			}
            if(this.majorTickMark !== oPr.majorTickMark){
            	return false;
			}
            if(this.minorTickMark !== oPr.minorTickMark){
            	return false;
			}
            if(this.tickLabelsPos !== oPr.tickLabelsPos){
            	return false;
			}
            if(this.crossesRule !== oPr.crossesRule){
            	return false;
			}
            if(this.crosses !== oPr.crosses){
            	return false;
			}
            if(this.axisType !== oPr.axisType){
            	return false;
			}

			return true;
		},

		putAxisType: function (v) {
			this.axisType = v;
		},

		putMinValRule: function (v) {
			this.minValRule = v;
		}, putMinVal: function (v) {
			this.minVal = v;
		}, putMaxValRule: function (v) {
			this.maxValRule = v;
		}, putMaxVal: function (v) {
			this.maxVal = v;
		}, putInvertValOrder: function (v) {
			this.invertValOrder = v;
		}, putLogScale: function (v) {
			this.logScale = v;
		}, putLogBase: function (v) {
			this.logBase = v;
		}, putUnits: function (v) {
			this.units = v;
		}, putShowUnitsOnChart: function (v) {
			this.showUnitsOnChart = v;
		}, putMajorTickMark: function (v) {
			this.majorTickMark = v;
		}, putMinorTickMark: function (v) {
			this.minorTickMark = v;
		}, putTickLabelsPos: function (v) {
			this.tickLabelsPos = v;
		}, putCrossesRule: function (v) {
			this.crossesRule = v;
		}, putCrosses: function (v) {
			this.crosses = v;
		},


		putDispUnitsRule: function (v) {
			this.dispUnitsRule = v;
		},

		getAxisType: function () {
			return this.axisType;
		},

		getDispUnitsRule: function () {
			return this.dispUnitsRule;
		},

		getMinValRule: function () {
			return this.minValRule;
		}, getMinVal: function () {
			return this.minVal;
		}, getMaxValRule: function () {
			return this.maxValRule;
		}, getMaxVal: function () {
			return this.maxVal;
		}, getInvertValOrder: function () {
			return this.invertValOrder;
		}, getLogScale: function () {
			return this.logScale;
		}, getLogBase: function () {
			return this.logBase;
		}, getUnits: function () {
			return this.units;
		}, getShowUnitsOnChart: function () {
			return this.showUnitsOnChart;
		}, getMajorTickMark: function () {
			return this.majorTickMark;
		}, getMinorTickMark: function () {
			return this.minorTickMark;
		}, getTickLabelsPos: function () {
			return this.tickLabelsPos;
		}, getCrossesRule: function () {
			return this.crossesRule;
		}, getCrosses: function () {
			return this.crosses;
		}, setDefault: function () {
			this.putMinValRule(Asc.c_oAscValAxisRule.auto);
			this.putMaxValRule(Asc.c_oAscValAxisRule.auto);
			this.putTickLabelsPos(Asc.c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO);
			this.putInvertValOrder(false);
			this.putDispUnitsRule(Asc.c_oAscValAxUnits.none);
			this.putMajorTickMark(c_oAscTickMark.TICK_MARK_OUT);
			this.putMinorTickMark(c_oAscTickMark.TICK_MARK_NONE);
			this.putCrossesRule(Asc.c_oAscCrossesRule.auto);
		}
	};

	/** @constructor */
	function asc_CatAxisSettings() {
		this.intervalBetweenTick = null;
		this.intervalBetweenLabelsRule = null;
		this.intervalBetweenLabels = null;
		this.invertCatOrder = null;
		this.labelsAxisDistance = null;
		this.majorTickMark = null;
		this.minorTickMark = null;
		this.tickLabelsPos = null;
		this.crossesRule = null;
		this.crosses = null;
		this.labelsPosition = null;
		this.axisType = c_oAscAxisType.cat;
		this.crossMinVal = null;
		this.crossMaxVal = null;
	}

	asc_CatAxisSettings.prototype = {

		isEqual: function(oPr){
			if(!oPr){
				return false;
			}
            if(this.intervalBetweenTick !== oPr.intervalBetweenTick){
            	return false;
			}
            if(this.intervalBetweenLabelsRule !== oPr.intervalBetweenLabelsRule){
            	return false;
			}
            if(this.intervalBetweenLabels !== oPr.intervalBetweenLabels){
            	return false;
			}
            if(this.invertCatOrder !== oPr.invertCatOrder){
            	return false;
			}
            if(this.labelsAxisDistance !== oPr.labelsAxisDistance){
            	return false;
			}
            if(this.majorTickMark !== oPr.majorTickMark){
            	return false;
			}
            if(this.minorTickMark !== oPr.minorTickMark){
            	return false;
			}
            if(this.tickLabelsPos !== oPr.tickLabelsPos){
            	return false;
			}
            if(this.crossesRule !== oPr.crossesRule){
            	return false;
			}
            if(this.crosses !== oPr.crosses){
            	return false;
			}
            if(this.labelsPosition !== oPr.labelsPosition){
            	return false;
			}
            if(this.axisType !==  oPr.axisType){
            	return false;
			}
            if(this.crossMinVal !== oPr.crossMinVal){
            	return false;
			}
            if(this.crossMaxVal !== oPr.crossMaxVal){
            	return false;
			}
			return true;
		},
		putIntervalBetweenTick: function (v) {
			this.intervalBetweenTick = v;
		}, putIntervalBetweenLabelsRule: function (v) {
			this.intervalBetweenLabelsRule = v;
		}, putIntervalBetweenLabels: function (v) {
			this.intervalBetweenLabels = v;
		}, putInvertCatOrder: function (v) {
			this.invertCatOrder = v;
		}, putLabelsAxisDistance: function (v) {
			this.labelsAxisDistance = v;
		}, putMajorTickMark: function (v) {
			this.majorTickMark = v;
		}, putMinorTickMark: function (v) {
			this.minorTickMark = v;
		}, putTickLabelsPos: function (v) {
			this.tickLabelsPos = v;
		}, putCrossesRule: function (v) {
			this.crossesRule = v;
		}, putCrosses: function (v) {
			this.crosses = v;
		},

		putAxisType: function (v) {
			this.axisType = v;
		},

		putLabelsPosition: function (v) {
			this.labelsPosition = v;
		},

		getIntervalBetweenTick: function (v) {
			return this.intervalBetweenTick;
		},

		getIntervalBetweenLabelsRule: function () {
			return this.intervalBetweenLabelsRule;
		}, getIntervalBetweenLabels: function () {
			return this.intervalBetweenLabels;
		}, getInvertCatOrder: function () {
			return this.invertCatOrder;
		}, getLabelsAxisDistance: function () {
			return this.labelsAxisDistance;
		}, getMajorTickMark: function () {
			return this.majorTickMark;
		}, getMinorTickMark: function () {
			return this.minorTickMark;
		}, getTickLabelsPos: function () {
			return this.tickLabelsPos;
		}, getCrossesRule: function () {
			return this.crossesRule;
		}, getCrosses: function () {
			return this.crosses;
		},

		getAxisType: function () {
			return this.axisType;
		},

		getLabelsPosition: function () {
			return this.labelsPosition;
		},

		getCrossMinVal: function () {
			return this.crossMinVal;
		},

		getCrossMaxVal: function () {
			return this.crossMaxVal;
		},


		putCrossMinVal: function (val) {
			this.crossMinVal = val;
		},

		putCrossMaxVal: function (val) {
			this.crossMaxVal = val;
		},

		setDefault: function () {
			this.putIntervalBetweenLabelsRule(Asc.c_oAscBetweenLabelsRule.auto);
			this.putLabelsPosition(Asc.c_oAscLabelsPosition.betweenDivisions);
			this.putTickLabelsPos(Asc.c_oAscTickLabelsPos.TICK_LABEL_POSITION_NEXT_TO);
			this.putLabelsAxisDistance(100);
			this.putMajorTickMark(c_oAscTickMark.TICK_MARK_OUT);
			this.putMinorTickMark(c_oAscTickMark.TICK_MARK_NONE);
			this.putIntervalBetweenTick(1);
			this.putCrossesRule(Asc.c_oAscCrossesRule.auto);
		}
	};

	/** @constructor */
	function asc_ChartSettings() {
		this.style = null;
		this.title = null;
		this.rowCols = null;
		this.horAxisLabel = null;
		this.vertAxisLabel = null;
		this.legendPos = null;
		this.dataLabelsPos = null;
		this.vertAx = null;
		this.horAx = null;
		this.horGridLines = null;
		this.vertGridLines = null;
		this.type = null;
		this.showSerName = null;
		this.showCatName = null;
		this.showVal = null;
		this.separator = null;
		this.horAxisProps = null;
		this.vertAxisProps = null;
		this.range = null;
		this.inColumns = null;

		this.showMarker = null;
		this.bLine = null;
		this.smooth = null;
		this.showHorAxis = null;
		this.showVerAxis = null;
	}

	asc_ChartSettings.prototype = {

		equalBool: function(a, b){
			return ((!!a) === (!!b));
		},

		isEqual: function(oPr){
			if(!oPr){
				return false;
			}
			if(this.style !== oPr.style){
				return false;
			}
            if(this.title !== oPr.title){
				return false;
			}
			if(this.rowCols !== oPr.rowCols){
            	return false;
			}
			if(this.horAxisLabel !== oPr.horAxisLabel){
				return false;
			}
            if(this.vertAxisLabel !== oPr.vertAxisLabel){
				return false;
			}
			if(this.legendPos !== oPr.legendPos){
           		return false;
			}
			if(this.dataLabelsPos !== oPr.dataLabelsPos){
				return false;
			}
			if(this.vertAx !== oPr.vertAx){
				return false;
			}
			if(this.horAx !== oPr.horAx){
				return false;
			}
            if(this.horGridLines !== oPr.horGridLines){
            	return false;
			}
            if(this.vertGridLines !== oPr.vertGridLines){
            	return false;
			}
            if(this.type !== oPr.type){
            	return false;
			}
            if(!this.equalBool(this.showSerName, oPr.showSerName)){
            	return false;
			}

            if(!this.equalBool(this.showCatName, oPr.showCatName)){
            	return false;
			}
            if(!this.equalBool(this.showVal, oPr.showVal)){
            	return false;
			}

            if(this.separator !== oPr.separator &&
			!(this.separator === ' ' && oPr.separator == null || oPr.separator === ' ' && this.separator == null)){
            	return false;
			}
			if(!this.horAxisProps){
            	if(oPr.horAxisProps){
            		return false;
				}
			}
			else{
				if(!this.horAxisProps.isEqual(oPr.horAxisProps)){
					return false;
				}
			}
            if(!this.vertAxisProps){
                if(oPr.vertAxisProps){
                    return false;
                }
            }
            else{
                if(!this.vertAxisProps.isEqual(oPr.vertAxisProps)){
                    return false;
                }
            }
            if(this.range !== oPr.range){
                return false;
            }
            if(!this.equalBool(this.inColumns, oPr.inColumns)){
                return false;
            }

            if(!this.equalBool(this.showMarker, oPr.showMarker)){
                return false;
            }
            if(!this.equalBool(this.bLine, oPr.bLine)){
                return false;
            }
            if(!this.equalBool(this.smooth, oPr.smooth)){
                return false;
            }
            if(!this.equalBool(this.showHorAxis, oPr.showHorAxis)){
                return false;
            }

            if(!this.equalBool(this.showVerAxis, oPr.showVerAxis)){
                return false;
            }
            return true;
		},

		putShowMarker: function (v) {
			this.showMarker = v;
		},

		getShowMarker: function () {
			return this.showMarker;
		},

		putLine: function (v) {
			this.bLine = v;
		},

		getLine: function () {
			return this.bLine;
		},


		putSmooth: function (v) {
			this.smooth = v;
		},

		getSmooth: function () {
			return this.smooth;
		},

		putStyle: function (index) {
			this.style = parseInt(index, 10);
		},

		getStyle: function () {
			return this.style;
		},

		putRange: function (range) {
			this.range = range;
		},

		getRange: function () {
			return this.range;
		},

		putInColumns: function (inColumns) {
			this.inColumns = inColumns;
		},

		getInColumns: function () {
			return this.inColumns;
		},

		putTitle: function (v) {
			this.title = v;
		},

		getTitle: function () {
			return this.title;
		},

		putRowCols: function (v) {
			this.rowCols = v;
		},

		getRowCols: function () {
			return this.rowCols;
		},

		putHorAxisLabel: function (v) {
			this.horAxisLabel = v;
		}, putVertAxisLabel: function (v) {
			this.vertAxisLabel = v;
		}, putLegendPos: function (v) {
			this.legendPos = v;
		}, putDataLabelsPos: function (v) {
			this.dataLabelsPos = v;
		}, putCatAx: function (v) {
			this.vertAx = v;
		}, putValAx: function (v) {
			this.horAx = v;
		},

		getHorAxisLabel: function (v) {
			return this.horAxisLabel;
		}, getVertAxisLabel: function (v) {
			return this.vertAxisLabel;
		}, getLegendPos: function (v) {
			return this.legendPos;
		}, getDataLabelsPos: function (v) {
			return this.dataLabelsPos;
		}, getVertAx: function (v) {
			return this.vertAx;
		}, getHorAx: function (v) {
			return this.horAx;
		},

		putHorGridLines: function (v) {
			this.horGridLines = v;
		},

		getHorGridLines: function (v) {
			return this.horGridLines;
		},

		putVertGridLines: function (v) {
			this.vertGridLines = v;
		},

		getVertGridLines: function () {
			return this.vertGridLines;
		},

		getType: function () {
			return this.type;
		},

		putType: function (v) {
			return this.type = v;
		},

		putShowSerName: function (v) {
			return this.showSerName = v;
		}, putShowCatName: function (v) {
			return this.showCatName = v;
		}, putShowVal: function (v) {
			return this.showVal = v;
		},


		getShowSerName: function () {
			return this.showSerName;
		}, getShowCatName: function () {
			return this.showCatName;
		}, getShowVal: function () {
			return this.showVal;
		},

		putSeparator: function (v) {
			this.separator = v;
		},

		getSeparator: function () {
			return this.separator;
		},

		putHorAxisProps: function (v) {
			this.horAxisProps = v;
		},

		getHorAxisProps: function () {
			return this.horAxisProps;
		},


		putVertAxisProps: function (v) {
			this.vertAxisProps = v;
		},

		getVertAxisProps: function () {
			return this.vertAxisProps;
		},



		checkSwapAxisProps: function(bHBar){
            var hor_axis_settings = this.getHorAxisProps();
            var vert_axis_settings = this.getVertAxisProps();
			if(!bHBar){
                if(hor_axis_settings){
                    if(hor_axis_settings.getAxisType() !== c_oAscAxisType.cat){
                        if(vert_axis_settings &&  vert_axis_settings.getAxisType() === c_oAscAxisType.cat){
                            this.putHorAxisProps(vert_axis_settings);
                        }
                        else{
                            var new_hor_axis_settings = new asc_CatAxisSettings();
                            new_hor_axis_settings.setDefault();
                            this.putHorAxisProps(new_hor_axis_settings);
                        }
                    }
                }
                else{
                    var new_hor_axis_settings = new asc_CatAxisSettings();
                    new_hor_axis_settings.setDefault();
                    this.putHorAxisProps(new_hor_axis_settings);
                }

                if(vert_axis_settings){
                    if(vert_axis_settings.getAxisType() !== c_oAscAxisType.val){
                        if(hor_axis_settings && hor_axis_settings.getAxisType() === c_oAscAxisType.val){
                            this.putVertAxisProps(hor_axis_settings);
                        }
                        else{
                            var new_vert_axis_settings = new asc_ValAxisSettings();
                            new_vert_axis_settings.setDefault();
                            this.putVertAxisProps(new_vert_axis_settings);
                        }
                    }
                }
                else{
                    var new_vert_axis_settings = new asc_ValAxisSettings();
                    new_vert_axis_settings.setDefault();
                    this.putVertAxisProps(new_vert_axis_settings);
                }
            }
            else{
                if(hor_axis_settings){
                    if(hor_axis_settings.getAxisType() !== c_oAscAxisType.val){
                        if(vert_axis_settings &&  vert_axis_settings.getAxisType() === c_oAscAxisType.val){
                            this.putHorAxisProps(vert_axis_settings);
                        }
                        else{
                            var new_hor_axis_settings = new asc_ValAxisSettings();
                            new_hor_axis_settings.setDefault();
                            this.putHorAxisProps(new_hor_axis_settings);
                        }
                    }
                }
                else{
                    var new_hor_axis_settings = new asc_ValAxisSettings();
                    new_hor_axis_settings.setDefault();
                    this.putHorAxisProps(new_hor_axis_settings);
                }

                if(vert_axis_settings){
                    if(vert_axis_settings.getAxisType() !== c_oAscAxisType.cat){
                        if(hor_axis_settings && hor_axis_settings.getAxisType() === c_oAscAxisType.cat){
                            this.putVertAxisProps(hor_axis_settings);
                        }
                        else{
                            var new_vert_axis_settings = new asc_CatAxisSettings();
                            new_vert_axis_settings.setDefault();
                            this.putVertAxisProps(new_vert_axis_settings);
                        }
                    }
                }
                else{
                    var new_vert_axis_settings = new asc_CatAxisSettings();
                    new_vert_axis_settings.setDefault();
                    this.putVertAxisProps(new_vert_axis_settings);
                }
			}
		},

		changeType: function (type) {
			if(null === this.type){
				this.putType(type);
				return;
			}
			if (this.type === type) {
				return;
			}

			var bSwapGridLines = ((this.type === c_oAscChartTypeSettings.hBarNormal ||
			this.type === c_oAscChartTypeSettings.hBarStacked || this.type === c_oAscChartTypeSettings.hBarStackedPer
			|| this.type === c_oAscChartTypeSettings.hBarNormal3d || this.type === c_oAscChartTypeSettings.hBarStacked3d
			|| this.type === c_oAscChartTypeSettings.hBarStackedPer3d) !==
			(type === c_oAscChartTypeSettings.hBarNormal || type === c_oAscChartTypeSettings.hBarStacked ||
			type === c_oAscChartTypeSettings.hBarStackedPer || this.type === c_oAscChartTypeSettings.hBarNormal3d
			|| this.type === c_oAscChartTypeSettings.hBarStacked3d || this.type === c_oAscChartTypeSettings.hBarStackedPer3d)   );
			var bSwapLines = ((
				type === c_oAscChartTypeSettings.lineNormal || type === c_oAscChartTypeSettings.lineStacked ||
				type === c_oAscChartTypeSettings.lineStackedPer || type === c_oAscChartTypeSettings.lineNormalMarker ||
				type === c_oAscChartTypeSettings.lineStackedMarker || type === c_oAscChartTypeSettings.lineStackedPerMarker || type === c_oAscChartTypeSettings.line3d

			) !== (

				this.type === c_oAscChartTypeSettings.lineNormal || this.type === c_oAscChartTypeSettings.lineStacked ||
				this.type === c_oAscChartTypeSettings.lineStackedPer ||
				this.type === c_oAscChartTypeSettings.lineNormalMarker ||
				this.type === c_oAscChartTypeSettings.lineStackedMarker ||
				this.type === c_oAscChartTypeSettings.lineStackedPerMarker ||
				this.type === c_oAscChartTypeSettings.line3d
			));
			var bSwapScatter = ((this.type === c_oAscChartTypeSettings.scatter) !==
			(type === c_oAscChartTypeSettings.scatter));


			var nOldType = this.type;
			this.putType(type);

			var hor_axis_settings = this.getHorAxisProps();
			var vert_axis_settings = this.getVertAxisProps();
			var new_hor_axis_settings, new_vert_axis_settings, oTempVal;
			if (bSwapGridLines) {
				oTempVal = hor_axis_settings;
				hor_axis_settings = vert_axis_settings;
				vert_axis_settings = oTempVal;
				this.putHorAxisProps(hor_axis_settings);
				this.putVertAxisProps(vert_axis_settings);

				oTempVal = this.horGridLines;
				this.putHorGridLines(this.vertGridLines);
				this.putVertGridLines(oTempVal);
			}
			switch (type) {
				case c_oAscChartTypeSettings.pie                 :
				case c_oAscChartTypeSettings.pie3d                 :
				case c_oAscChartTypeSettings.doughnut            : {
					this.putHorAxisProps(null);
					this.putVertAxisProps(null);
					this.putHorAxisLabel(null);
					this.putVertAxisLabel(null);
					this.putShowHorAxis(null);
					this.putShowVerAxis(null);
					break;
				}
				case c_oAscChartTypeSettings.barNormal           :
				case c_oAscChartTypeSettings.barStacked          :
				case c_oAscChartTypeSettings.barStackedPer       :
				case c_oAscChartTypeSettings.barNormal3d         :
				case c_oAscChartTypeSettings.barStacked3d        :
				case c_oAscChartTypeSettings.barStackedPer3d     :
				case c_oAscChartTypeSettings.barNormal3dPerspective     :
				case c_oAscChartTypeSettings.lineNormal          :
				case c_oAscChartTypeSettings.lineStacked         :
				case c_oAscChartTypeSettings.lineStackedPer      :
				case c_oAscChartTypeSettings.lineNormalMarker    :
				case c_oAscChartTypeSettings.lineStackedMarker   :
				case c_oAscChartTypeSettings.lineStackedPerMarker:
				case c_oAscChartTypeSettings.line3d:
				case c_oAscChartTypeSettings.areaNormal          :
				case c_oAscChartTypeSettings.areaStacked         :
				case c_oAscChartTypeSettings.areaStackedPer      :
				case c_oAscChartTypeSettings.stock               :
                case c_oAscChartTypeSettings.surfaceNormal       :
                case c_oAscChartTypeSettings.surfaceWireframe    :
                case c_oAscChartTypeSettings.contourNormal       :
                case c_oAscChartTypeSettings.contourWireframe    :
					{



                        this.checkSwapAxisProps(false);
					if (bSwapLines) {
						this.putShowMarker(false);
						this.putSmooth(null);
						this.putLine(true);
					}
					if (nOldType === c_oAscChartTypeSettings.hBarNormal || nOldType === c_oAscChartTypeSettings.hBarStacked ||
						nOldType === c_oAscChartTypeSettings.hBarStackedPer || nOldType === c_oAscChartTypeSettings.hBarNormal3d ||
						nOldType === c_oAscChartTypeSettings.hBarStacked3d || nOldType === c_oAscChartTypeSettings.hBarStackedPer3d) {
						var bTemp = this.showHorAxis;
						this.putShowHorAxis(this.showVerAxis);
						this.putShowVerAxis(bTemp);
					} else if (nOldType === c_oAscChartTypeSettings.pie || nOldType === c_oAscChartTypeSettings.pie3d || nOldType === c_oAscChartTypeSettings.doughnut) {
						this.putShowHorAxis(true);
						this.putShowVerAxis(true);
					}
					var oHorAxisProps = this.getHorAxisProps();
						if(oHorAxisProps && oHorAxisProps.getAxisType() === c_oAscAxisType.cat){
							if(type === c_oAscChartTypeSettings.areaNormal ||
							type === c_oAscChartTypeSettings.areaStacked ||
							type === c_oAscChartTypeSettings.areaStackedPer||
							type === c_oAscChartTypeSettings.stock ||
							type === c_oAscChartTypeSettings.surfaceNormal ||
							type === c_oAscChartTypeSettings.surfaceWireframe ||
							type === c_oAscChartTypeSettings.contourNormal ||
							type === c_oAscChartTypeSettings.contourWireframe){
								oHorAxisProps.putLabelsPosition(Asc.c_oAscLabelsPosition.byDivisions);
							}
							else{
								oHorAxisProps.putLabelsPosition(Asc.c_oAscLabelsPosition.betweenDivisions);
							}
						}
					break;
				}
				case c_oAscChartTypeSettings.hBarNormal          :
				case c_oAscChartTypeSettings.hBarStacked         :
				case c_oAscChartTypeSettings.hBarStackedPer      :
                case c_oAscChartTypeSettings.hBarNormal3d        :
                case c_oAscChartTypeSettings.hBarStacked3d       :
                case c_oAscChartTypeSettings.hBarStackedPer3d    :
					{
                        this.checkSwapAxisProps(true);
					if (nOldType === c_oAscChartTypeSettings.pie || nOldType === c_oAscChartTypeSettings.pie3d || nOldType === c_oAscChartTypeSettings.doughnut) {
						this.putShowHorAxis(true);
						this.putShowVerAxis(true);
					} else if (nOldType !== c_oAscChartTypeSettings.hBarNormal &&
						nOldType !== c_oAscChartTypeSettings.hBarStacked && nOldType !== c_oAscChartTypeSettings.hBarStackedPer || nOldType !== c_oAscChartTypeSettings.hBarNormal3d ||
                        nOldType !== c_oAscChartTypeSettings.hBarStacked3d || nOldType !== c_oAscChartTypeSettings.hBarStackedPer3d) {
						var bTemp = this.showHorAxis;
						this.putShowHorAxis(this.showVerAxis);
						this.putShowVerAxis(bTemp);
					}

					var oVertAxisProps = this.getVertAxisProps();
					if(oVertAxisProps && oVertAxisProps.getAxisType() === c_oAscAxisType.cat){
						oVertAxisProps.putLabelsPosition(Asc.c_oAscLabelsPosition.betweenDivisions);
					}
					//this.putHorGridLines(c_oAscGridLinesSettings.none);
					//this.putVertGridLines(c_oAscGridLinesSettings.major);
					break;
				}
				case c_oAscChartTypeSettings.scatter             :
				case c_oAscChartTypeSettings.scatterLine         :
				case c_oAscChartTypeSettings.scatterLineMarker   :
				case c_oAscChartTypeSettings.scatterMarker       :
				case c_oAscChartTypeSettings.scatterNone         :
				case c_oAscChartTypeSettings.scatterSmooth       :
				case c_oAscChartTypeSettings.scatterSmoothMarker : {
					if (!hor_axis_settings || hor_axis_settings.getAxisType() !== c_oAscAxisType.val) {
						new_hor_axis_settings = new asc_ValAxisSettings();
						new_hor_axis_settings.setDefault();
						this.putHorAxisProps(new_hor_axis_settings);
					}
					if (!vert_axis_settings || vert_axis_settings.getAxisType() !== c_oAscAxisType.val) {
						new_vert_axis_settings = new asc_ValAxisSettings();
						new_vert_axis_settings.setDefault();
						this.putVertAxisProps(new_vert_axis_settings);
					}
					//this.putHorGridLines(c_oAscGridLinesSettings.major);
					//this.putVertGridLines(c_oAscGridLinesSettings.major);
					if (bSwapScatter) {
						this.putShowMarker(true);
						this.putSmooth(null);
						this.putLine(false);
					}
					if (nOldType === c_oAscChartTypeSettings.hBarNormal || nOldType === c_oAscChartTypeSettings.hBarStacked ||
						nOldType === c_oAscChartTypeSettings.hBarStackedPer || nOldType === c_oAscChartTypeSettings.hBarNormal3d ||
                        nOldType === c_oAscChartTypeSettings.hBarStacked3d || nOldType === c_oAscChartTypeSettings.hBarStackedPer3d) {
						var bTemp = this.showHorAxis;
						this.putShowHorAxis(this.showVerAxis);
						this.putShowVerAxis(bTemp);
					} else if (nOldType === c_oAscChartTypeSettings.pie || nOldType === c_oAscChartTypeSettings.pie3d || nOldType === c_oAscChartTypeSettings.doughnut) {
						this.putShowHorAxis(true);
						this.putShowVerAxis(true);
					}
					break;
				}
			}
		},

		putShowHorAxis: function (v) {
			this.showHorAxis = v;
		}, getShowHorAxis: function () {
			return this.showHorAxis;
		},

		putShowVerAxis: function (v) {
			this.showVerAxis = v;
		}, getShowVerAxis: function () {
			return this.showVerAxis;
		}
	};

	/** @constructor */
	function asc_CRect(x, y, width, height) {
		// private members
		this._x = x;
		this._y = y;
		this._width = width;
		this._height = height;
	}

	asc_CRect.prototype = {
		asc_getX: function () {
			return this._x;
		}, asc_getY: function () {
			return this._y;
		}, asc_getWidth: function () {
			return this._width;
		}, asc_getHeight: function () {
			return this._height;
		}
	};

	/**
	 * Класс CColor для работы с цветами
	 * -----------------------------------------------------------------------------
	 *
	 * @constructor
	 * @memberOf window
	 */

	function CColor(r, g, b, a) {
		this.r = (undefined == r) ? 0 : r;
		this.g = (undefined == g) ? 0 : g;
		this.b = (undefined == b) ? 0 : b;
		this.a = (undefined == a) ? 1 : a;
	}

	CColor.prototype = {
		constructor: CColor, getR: function () {
			return this.r
		}, get_r: function () {
			return this.r
		}, put_r: function (v) {
			this.r = v;
			this.hex = undefined;
		}, getG: function () {
			return this.g
		}, get_g: function () {
			return this.g;
		}, put_g: function (v) {
			this.g = v;
			this.hex = undefined;
		}, getB: function () {
			return this.b
		}, get_b: function () {
			return this.b;
		}, put_b: function (v) {
			this.b = v;
			this.hex = undefined;
		}, getA: function () {
			return this.a
		}, get_hex: function () {
			if (!this.hex) {
				var r = this.r.toString(16);
				var g = this.g.toString(16);
				var b = this.b.toString(16);
				this.hex = ( r.length == 1 ? "0" + r : r) + ( g.length == 1 ? "0" + g : g) + ( b.length == 1 ? "0" + b : b);
			}
			return this.hex;
		},

		Compare: function (Color) {
			return (this.r === Color.r && this.g === Color.g && this.b === Color.b && this.a === Color.a);
		}, Copy: function () {
			return new CColor(this.r, this.g, this.b, this.a);
		}
	};

	/** @constructor */
	function asc_CColor() {
		this.type = c_oAscColor.COLOR_TYPE_SRGB;
		this.value = null;
		this.r = 0;
		this.g = 0;
		this.b = 0;
		this.a = 255;

		this.Auto = false;

		this.Mods = [];
		this.ColorSchemeId = -1;

		if (1 === arguments.length) {
			this.r = arguments[0].r;
			this.g = arguments[0].g;
			this.b = arguments[0].b;
		} else {
			if (3 <= arguments.length) {
				this.r = arguments[0];
				this.g = arguments[1];
				this.b = arguments[2];
			}
        if (4 === arguments.length) {
            this.a = arguments[3];
        }
		}
	}

	asc_CColor.prototype = {
		constructor: asc_CColor, asc_getR: function () {
			return this.r
		}, asc_putR: function (v) {
			this.r = v;
			this.hex = undefined;
		}, asc_getG: function () {
			return this.g;
		}, asc_putG: function (v) {
			this.g = v;
			this.hex = undefined;
		}, asc_getB: function () {
			return this.b;
		}, asc_putB: function (v) {
			this.b = v;
			this.hex = undefined;
		}, asc_getA: function () {
			return this.a;
		}, asc_putA: function (v) {
			this.a = v;
			this.hex = undefined;
		}, asc_getType: function () {
			return this.type;
		}, asc_putType: function (v) {
			this.type = v;
		}, asc_getValue: function () {
			return this.value;
		}, asc_putValue: function (v) {
			this.value = v;
		}, asc_getHex: function () {
			if (!this.hex) {
				var a = this.a.toString(16);
				var r = this.r.toString(16);
				var g = this.g.toString(16);
				var b = this.b.toString(16);
				this.hex = ( a.length == 1 ? "0" + a : a) + ( r.length == 1 ? "0" + r : r) + ( g.length == 1 ? "0" + g : g) +
					( b.length == 1 ? "0" + b : b);
			}
			return this.hex;
		}, asc_getColor: function () {
			return new CColor(this.r, this.g, this.b);
		}, asc_putAuto: function (v) {
			this.Auto = v;
		}, asc_getAuto: function () {
			return this.Auto;
		}
	};

	/** @constructor */
	function asc_CTextBorder(obj) {
		if (obj) {
			if (obj.Color instanceof asc_CColor) {
				this.Color = obj.Color;
			} else {
				this.Color =
					(undefined != obj.Color && null != obj.Color) ? CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) :
						null;
			}
			this.Size = (undefined != obj.Size) ? obj.Size : null;
			this.Value = (undefined != obj.Value) ? obj.Value : null;
			this.Space = (undefined != obj.Space) ? obj.Space : null;
		} else {
			this.Color = CreateAscColorCustom(0, 0, 0);
			this.Size = 0.5 * window["AscCommonWord"].g_dKoef_pt_to_mm;
			this.Value = window["AscCommonWord"].border_Single;
			this.Space = 0;
		}
	}

	asc_CTextBorder.prototype.asc_getColor = function () {
		return this.Color;
	};
	asc_CTextBorder.prototype.asc_putColor = function (v) {
		this.Color = v;
	};
	asc_CTextBorder.prototype.asc_getSize = function () {
		return this.Size;
	};
	asc_CTextBorder.prototype.asc_putSize = function (v) {
		this.Size = v;
	};
	asc_CTextBorder.prototype.asc_getValue = function () {
		return this.Value;
	};
	asc_CTextBorder.prototype.asc_putValue = function (v) {
		this.Value = v;
	};
	asc_CTextBorder.prototype.asc_getSpace = function () {
		return this.Space;
	};
	asc_CTextBorder.prototype.asc_putSpace = function (v) {
		this.Space = v;
	};
	asc_CTextBorder.prototype.asc_getForSelectedCells = function () {
		return this.ForSelectedCells;
	};
	asc_CTextBorder.prototype.asc_putForSelectedCells = function (v) {
		this.ForSelectedCells = v;
	};

	/** @constructor */
	function asc_CParagraphBorders(obj) {

		if (obj) {
			this.Left = (undefined != obj.Left && null != obj.Left) ? new asc_CTextBorder(obj.Left) : null;
			this.Top = (undefined != obj.Top && null != obj.Top) ? new asc_CTextBorder(obj.Top) : null;
			this.Right = (undefined != obj.Right && null != obj.Right) ? new asc_CTextBorder(obj.Right) : null;
			this.Bottom = (undefined != obj.Bottom && null != obj.Bottom) ? new asc_CTextBorder(obj.Bottom) : null;
			this.Between = (undefined != obj.Between && null != obj.Between) ? new asc_CTextBorder(obj.Between) : null;
		} else {
			this.Left = null;
			this.Top = null;
			this.Right = null;
			this.Bottom = null;
			this.Between = null;
		}
	}

	asc_CParagraphBorders.prototype = {
		asc_getLeft: function () {
			return this.Left;
		}, asc_putLeft: function (v) {
			this.Left = (v) ? new asc_CTextBorder(v) : null;
		}, asc_getTop: function () {
			return this.Top;
		}, asc_putTop: function (v) {
			this.Top = (v) ? new asc_CTextBorder(v) : null;
		}, asc_getRight: function () {
			return this.Right;
		}, asc_putRight: function (v) {
			this.Right = (v) ? new asc_CTextBorder(v) : null;
		}, asc_getBottom: function () {
			return this.Bottom;
		}, asc_putBottom: function (v) {
			this.Bottom = (v) ? new asc_CTextBorder(v) : null;
		}, asc_getBetween: function () {
			return this.Between;
		}, asc_putBetween: function (v) {
			this.Between = (v) ? new asc_CTextBorder(v) : null;
		}
	};

	/** @constructor */
	function asc_CListType(obj) {

		if (obj) {
			this.Type = (undefined == obj.Type) ? null : obj.Type;
			this.SubType = (undefined == obj.Type) ? null : obj.SubType;
		} else {
			this.Type = null;
			this.SubType = null;
		}
	}

	asc_CListType.prototype.asc_getListType = function () {
		return this.Type;
	};
	asc_CListType.prototype.asc_getListSubType = function () {
		return this.SubType;
	};

	/** @constructor */
	function asc_CTextFontFamily(obj) {

		if (obj) {
			this.Name = (undefined != obj.Name) ? obj.Name : null; 		// "Times New Roman"
			this.Index = (undefined != obj.Index) ? obj.Index : null;	// -1
		} else {
			this.Name = "Times New Roman";
			this.Index = -1;
		}
	}

	asc_CTextFontFamily.prototype = {
		asc_getName: function () {
			return this.Name;
		}, asc_getIndex: function () {
			return this.Index;
		}
	};

	/** @constructor */
	function asc_CParagraphTab(Pos, Value, Leader)
	{
		this.Pos    = Pos;
		this.Value  = Value;
		this.Leader = Leader;
	}
	asc_CParagraphTab.prototype.asc_getValue = function()
	{
		return this.Value;
	};
	asc_CParagraphTab.prototype.asc_putValue = function(v)
	{
		this.Value = v;
	};
	asc_CParagraphTab.prototype.asc_getPos = function()
	{
		return this.Pos;
	};
	asc_CParagraphTab.prototype.asc_putPos = function(v)
	{
		this.Pos = v;
	};
	asc_CParagraphTab.prototype.asc_getLeader = function()
	{
		if (Asc.c_oAscTabLeader.Heavy === this.Leader)
			return Asc.c_oAscTabLeader.Underscore;

		return this.Leader;
	};
	asc_CParagraphTab.prototype.asc_putLeader = function(v)
	{
		this.Leader = v;
	};

	/** @constructor */
	function asc_CParagraphTabs(obj) {
		this.Tabs = [];

		if (undefined != obj) {
			var Count = obj.Tabs.length;
			for (var Index = 0; Index < Count; Index++) {
				this.Tabs.push(new asc_CParagraphTab(obj.Tabs[Index].Pos, obj.Tabs[Index].Value, obj.Tabs[Index].Leader));
			}
		}
	}

	asc_CParagraphTabs.prototype = {
		asc_getCount: function () {
			return this.Tabs.length;
		}, asc_getTab: function (Index) {
			return this.Tabs[Index];
		}, asc_addTab: function (Tab) {
			this.Tabs.push(Tab)
		}, asc_clear: function () {
			this.Tabs.length = 0;
		}
	};

	/** @constructor */
	function asc_CParagraphShd(obj) {

		if (obj) {
			this.Value = (undefined != obj.Value) ? obj.Value : null;
			if (obj.Unifill && obj.Unifill.fill && obj.Unifill.fill.type === c_oAscFill.FILL_TYPE_SOLID &&
				obj.Unifill.fill.color) {
				this.Color = CreateAscColor(obj.Unifill.fill.color);
			} else {
				this.Color =
					(undefined != obj.Color && null != obj.Color) ? CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) :
						null;
			}
		} else {
			this.Value = Asc.c_oAscShdNil;
			this.Color = CreateAscColorCustom(255, 255, 255);
		}
	}

	asc_CParagraphShd.prototype = {
		asc_getValue: function () {
			return this.Value;
		}, asc_putValue: function (v) {
			this.Value = v;
		}, asc_getColor: function () {
			return this.Color;
		}, asc_putColor: function (v) {
			this.Color = (v) ? v : null;
		}
	};

	/** @constructor */
	function asc_CParagraphFrame(obj) {
		if (obj) {
			this.FromDropCapMenu = false;

			this.DropCap = obj.DropCap;
			this.H = obj.H;
			this.HAnchor = obj.HAnchor;
			this.HRule = obj.HRule;
			this.HSpace = obj.HSpace;
			this.Lines = obj.Lines;
			this.VAnchor = obj.VAnchor;
			this.VSpace = obj.VSpace;
			this.W = obj.W;
			this.Wrap = obj.Wrap;
			this.X = obj.X;
			this.XAlign = obj.XAlign;
			this.Y = obj.Y;
			this.YAlign = obj.YAlign;
			this.Brd = (undefined != obj.Brd && null != obj.Brd) ? new asc_CParagraphBorders(obj.Brd) : null;
			this.Shd = (undefined != obj.Shd && null != obj.Shd) ? new asc_CParagraphShd(obj.Shd) : null;
			this.FontFamily =
				(undefined != obj.FontFamily && null != obj.FontFamily) ? new asc_CTextFontFamily(obj.FontFamily) : null;
		} else {
			this.FromDropCapMenu = false;

			this.DropCap = undefined;
			this.H = undefined;
			this.HAnchor = undefined;
			this.HRule = undefined;
			this.HSpace = undefined;
			this.Lines = undefined;
			this.VAnchor = undefined;
			this.VSpace = undefined;
			this.W = undefined;
			this.Wrap = undefined;
			this.X = undefined;
			this.XAlign = undefined;
			this.Y = undefined;
			this.YAlign = undefined;
			this.Shd = null;
			this.Brd = null;
			this.FontFamily = null;
		}
	}

	asc_CParagraphFrame.prototype.asc_getDropCap = function () {
		return this.DropCap;
	};
	asc_CParagraphFrame.prototype.asc_putDropCap = function (v) {
		this.DropCap = v;
	};
	asc_CParagraphFrame.prototype.asc_getH = function () {
		return this.H;
	};
	asc_CParagraphFrame.prototype.asc_putH = function (v) {
		this.H = v;
	};
	asc_CParagraphFrame.prototype.asc_getHAnchor = function () {
		return this.HAnchor;
	};
	asc_CParagraphFrame.prototype.asc_putHAnchor = function (v) {
		this.HAnchor = v;
	};
	asc_CParagraphFrame.prototype.asc_getHRule = function () {
		return this.HRule;
	};
	asc_CParagraphFrame.prototype.asc_putHRule = function (v) {
		this.HRule = v;
	};
	asc_CParagraphFrame.prototype.asc_getHSpace = function () {
		return this.HSpace;
	};
	asc_CParagraphFrame.prototype.asc_putHSpace = function (v) {
		this.HSpace = v;
	};
	asc_CParagraphFrame.prototype.asc_getLines = function () {
		return this.Lines;
	};
	asc_CParagraphFrame.prototype.asc_putLines = function (v) {
		this.Lines = v;
	};
	asc_CParagraphFrame.prototype.asc_getVAnchor = function () {
		return this.VAnchor;
	};
	asc_CParagraphFrame.prototype.asc_putVAnchor = function (v) {
		this.VAnchor = v;
	};
	asc_CParagraphFrame.prototype.asc_getVSpace = function () {
		return this.VSpace;
	};
	asc_CParagraphFrame.prototype.asc_putVSpace = function (v) {
		this.VSpace = v;
	};
	asc_CParagraphFrame.prototype.asc_getW = function () {
		return this.W;
	};
	asc_CParagraphFrame.prototype.asc_putW = function (v) {
		this.W = v;
	};
	asc_CParagraphFrame.prototype.asc_getWrap = function () {
		return this.Wrap;
	};
	asc_CParagraphFrame.prototype.asc_putWrap = function (v) {
		this.Wrap = v;
	};
	asc_CParagraphFrame.prototype.asc_getX = function () {
		return this.X;
	};
	asc_CParagraphFrame.prototype.asc_putX = function (v) {
		this.X = v;
	};
	asc_CParagraphFrame.prototype.asc_getXAlign = function () {
		return this.XAlign;
	};
	asc_CParagraphFrame.prototype.asc_putXAlign = function (v) {
		this.XAlign = v;
	};
	asc_CParagraphFrame.prototype.asc_getY = function () {
		return this.Y;
	};
	asc_CParagraphFrame.prototype.asc_putY = function (v) {
		this.Y = v;
	};
	asc_CParagraphFrame.prototype.asc_getYAlign = function () {
		return this.YAlign;
	};
	asc_CParagraphFrame.prototype.asc_putYAlign = function (v) {
		this.YAlign = v;
	};
	asc_CParagraphFrame.prototype.asc_getBorders = function () {
		return this.Brd;
	};
	asc_CParagraphFrame.prototype.asc_putBorders = function (v) {
		this.Brd = v;
	};
	asc_CParagraphFrame.prototype.asc_getShade = function () {
		return this.Shd;
	};
	asc_CParagraphFrame.prototype.asc_putShade = function (v) {
		this.Shd = v;
	};
	asc_CParagraphFrame.prototype.asc_getFontFamily = function () {
		return this.FontFamily;
	};
	asc_CParagraphFrame.prototype.asc_putFontFamily = function (v) {
		this.FontFamily = v;
	};
	asc_CParagraphFrame.prototype.asc_putFromDropCapMenu = function (v) {
		this.FromDropCapMenu = v;
	};

	/** @constructor */
	function asc_CParagraphSpacing(obj) {

		if (obj) {
			this.Line = (undefined != obj.Line    ) ? obj.Line : null; // Расстояние между строками внутри абзаца
			this.LineRule = (undefined != obj.LineRule) ? obj.LineRule : null; // Тип расстрояния между строками
			this.Before = (undefined != obj.Before  ) ? obj.Before : null; // Дополнительное расстояние до абзаца
			this.After = (undefined != obj.After   ) ? obj.After : null; // Дополнительное расстояние после абзаца
		} else {
			this.Line = undefined; // Расстояние между строками внутри абзаца
			this.LineRule = undefined; // Тип расстрояния между строками
			this.Before = undefined; // Дополнительное расстояние до абзаца
			this.After = undefined; // Дополнительное расстояние после абзаца
		}
	}

	asc_CParagraphSpacing.prototype = {
		asc_getLine: function () {
			return this.Line;
		}, asc_getLineRule: function () {
			return this.LineRule;
		}, asc_getBefore: function () {
			return this.Before;
		}, asc_getAfter: function () {
			return this.After;
		}
	};

	/** @constructor */
	function asc_CParagraphInd(obj) {
		if (obj) {
			this.Left = (undefined != obj.Left     ) ? obj.Left : null; // Левый отступ
			this.Right = (undefined != obj.Right    ) ? obj.Right : null; // Правый отступ
			this.FirstLine = (undefined != obj.FirstLine) ? obj.FirstLine : null; // Первая строка
		} else {
			this.Left = undefined; // Левый отступ
			this.Right = undefined; // Правый отступ
			this.FirstLine = undefined; // Первая строка
		}
	}

	asc_CParagraphInd.prototype = {
		asc_getLeft: function () {
			return this.Left;
		}, asc_putLeft: function (v) {
			this.Left = v;
		}, asc_getRight: function () {
			return this.Right;
		}, asc_putRight: function (v) {
			this.Right = v;
		}, asc_getFirstLine: function () {
			return this.FirstLine;
		}, asc_putFirstLine: function (v) {
			this.FirstLine = v;
		}
	};

	/** @constructor */
	function asc_CParagraphProperty(obj) {

		if (obj) {
			this.ContextualSpacing = (undefined != obj.ContextualSpacing) ? obj.ContextualSpacing : null;
			this.Ind = (undefined != obj.Ind && null != obj.Ind) ? new asc_CParagraphInd(obj.Ind) : null;
			this.KeepLines = (undefined != obj.KeepLines) ? obj.KeepLines : null;
			this.KeepNext = (undefined != obj.KeepNext) ? obj.KeepNext : undefined;
			this.WidowControl = (undefined != obj.WidowControl ? obj.WidowControl : undefined );
			this.PageBreakBefore = (undefined != obj.PageBreakBefore) ? obj.PageBreakBefore : null;
			this.Spacing = (undefined != obj.Spacing && null != obj.Spacing) ? new asc_CParagraphSpacing(obj.Spacing) : null;
			this.Brd = (undefined != obj.Brd && null != obj.Brd) ? new asc_CParagraphBorders(obj.Brd) : null;
			this.Shd = (undefined != obj.Shd && null != obj.Shd) ? new asc_CParagraphShd(obj.Shd) : null;
			this.Tabs = (undefined != obj.Tabs) ? new asc_CParagraphTabs(obj.Tabs) : undefined;
			this.DefaultTab = obj.DefaultTab != null ? obj.DefaultTab : window["AscCommonWord"].Default_Tab_Stop;
			this.Locked = (undefined != obj.Locked && null != obj.Locked ) ? obj.Locked : false;
			this.CanAddTable = (undefined != obj.CanAddTable ) ? obj.CanAddTable : true;

			this.FramePr = (undefined != obj.FramePr ) ? new asc_CParagraphFrame(obj.FramePr) : undefined;
			this.CanAddDropCap = (undefined != obj.CanAddDropCap ) ? obj.CanAddDropCap : false;
			this.CanAddImage = (undefined != obj.CanAddImage ) ? obj.CanAddImage : false;

			this.Subscript = (undefined != obj.Subscript) ? obj.Subscript : undefined;
			this.Superscript = (undefined != obj.Superscript) ? obj.Superscript : undefined;
			this.SmallCaps = (undefined != obj.SmallCaps) ? obj.SmallCaps : undefined;
			this.AllCaps = (undefined != obj.AllCaps) ? obj.AllCaps : undefined;
			this.Strikeout = (undefined != obj.Strikeout) ? obj.Strikeout : undefined;
			this.DStrikeout = (undefined != obj.DStrikeout) ? obj.DStrikeout : undefined;
			this.TextSpacing = (undefined != obj.TextSpacing) ? obj.TextSpacing : undefined;
			this.Position = (undefined != obj.Position) ? obj.Position : undefined;
		} else {
			//ContextualSpacing : false,            // Удалять ли интервал между параграфами одинакового стиля
			//
			//    Ind :
			//    {
			//        Left      : 0,                    // Левый отступ
			//        Right     : 0,                    // Правый отступ
			//        FirstLine : 0                     // Первая строка
			//    },
			//
			//    Jc : align_Left,                      // Прилегание параграфа
			//
			//    KeepLines : false,                    // переносить параграф на новую страницу,
			//                                          // если на текущей он целиком не убирается
			//    KeepNext  : false,                    // переносить параграф вместе со следующим параграфом
			//
			//    PageBreakBefore : false,              // начинать параграф с новой страницы

			this.ContextualSpacing = undefined;
			this.Ind = new asc_CParagraphInd();
			this.KeepLines = undefined;
			this.KeepNext = undefined;
			this.WidowControl = undefined;
			this.PageBreakBefore = undefined;
			this.Spacing = new asc_CParagraphSpacing();
			this.Brd = undefined;
			this.Shd = undefined;
			this.Locked = false;
			this.CanAddTable = true;
			this.Tabs = undefined;

			this.Subscript = undefined;
			this.Superscript = undefined;
			this.SmallCaps = undefined;
			this.AllCaps = undefined;
			this.Strikeout = undefined;
			this.DStrikeout = undefined;
			this.TextSpacing = undefined;
			this.Position = undefined;
		}
	}

	asc_CParagraphProperty.prototype = {

		asc_getContextualSpacing: function () {
			return this.ContextualSpacing;
		}, asc_putContextualSpacing: function (v) {
			this.ContextualSpacing = v;
		}, asc_getInd: function () {
			return this.Ind;
		}, asc_putInd: function (v) {
			this.Ind = v;
		}, asc_getKeepLines: function () {
			return this.KeepLines;
		}, asc_putKeepLines: function (v) {
			this.KeepLines = v;
		}, asc_getKeepNext: function () {
			return this.KeepNext;
		}, asc_putKeepNext: function (v) {
			this.KeepNext = v;
		}, asc_getPageBreakBefore: function () {
			return this.PageBreakBefore;
		}, asc_putPageBreakBefore: function (v) {
			this.PageBreakBefore = v;
		}, asc_getWidowControl: function () {
			return this.WidowControl;
		}, asc_putWidowControl: function (v) {
			this.WidowControl = v;
		}, asc_getSpacing: function () {
			return this.Spacing;
		}, asc_putSpacing: function (v) {
			this.Spacing = v;
		}, asc_getBorders: function () {
			return this.Brd;
		}, asc_putBorders: function (v) {
			this.Brd = v;
		}, asc_getShade: function () {
			return this.Shd;
		}, asc_putShade: function (v) {
			this.Shd = v;
		}, asc_getLocked: function () {
			return this.Locked;
		}, asc_getCanAddTable: function () {
			return this.CanAddTable;
		}, asc_getSubscript: function () {
			return this.Subscript;
		}, asc_putSubscript: function (v) {
			this.Subscript = v;
		}, asc_getSuperscript: function () {
			return this.Superscript;
		}, asc_putSuperscript: function (v) {
			this.Superscript = v;
		}, asc_getSmallCaps: function () {
			return this.SmallCaps;
		}, asc_putSmallCaps: function (v) {
			this.SmallCaps = v;
		}, asc_getAllCaps: function () {
			return this.AllCaps;
		}, asc_putAllCaps: function (v) {
			this.AllCaps = v;
		}, asc_getStrikeout: function () {
			return this.Strikeout;
		}, asc_putStrikeout: function (v) {
			this.Strikeout = v;
		}, asc_getDStrikeout: function () {
			return this.DStrikeout;
		}, asc_putDStrikeout: function (v) {
			this.DStrikeout = v;
		}, asc_getTextSpacing: function () {
			return this.TextSpacing;
		}, asc_putTextSpacing: function (v) {
			this.TextSpacing = v;
		}, asc_getPosition: function () {
			return this.Position;
		}, asc_putPosition: function (v) {
			this.Position = v;
		}, asc_getTabs: function () {
			return this.Tabs;
		}, asc_putTabs: function (v) {
			this.Tabs = v;
		}, asc_getDefaultTab: function () {
			return this.DefaultTab;
		}, asc_putDefaultTab: function (v) {
			this.DefaultTab = v;
		},

		asc_getFramePr: function () {
			return this.FramePr;
		}, asc_putFramePr: function (v) {
			this.FramePr = v;
		}, asc_getCanAddDropCap: function () {
			return this.CanAddDropCap;
		}, asc_getCanAddImage: function () {
			return this.CanAddImage;
		}
	};

	/** @constructor */
	function asc_CTexture() {
		this.Id = 0;
		this.Image = "";
	}

	asc_CTexture.prototype = {
		asc_getId: function () {
			return this.Id;
		}, asc_getImage: function () {
			return this.Image;
		}
	};

	/** @constructor */
	function asc_CImageSize(width, height, isCorrect) {
		this.Width = (undefined == width) ? 0.0 : width;
		this.Height = (undefined == height) ? 0.0 : height;
		this.IsCorrect = isCorrect;
	}

	asc_CImageSize.prototype = {
		asc_getImageWidth: function () {
			return this.Width;
		}, asc_getImageHeight: function () {
			return this.Height;
		}, asc_getIsCorrect: function () {
			return this.IsCorrect;
		}
	};

	/** @constructor */
	function asc_CPaddings(obj) {

		if (obj) {
			this.Left = (undefined == obj.Left) ? null : obj.Left;
			this.Top = (undefined == obj.Top) ? null : obj.Top;
			this.Bottom = (undefined == obj.Bottom) ? null : obj.Bottom;
			this.Right = (undefined == obj.Right) ? null : obj.Right;
		} else {
			this.Left = null;
			this.Top = null;
			this.Bottom = null;
			this.Right = null;
		}
	}

	asc_CPaddings.prototype = {
		asc_getLeft: function () {
			return this.Left;
		}, asc_putLeft: function (v) {
			this.Left = v;
		}, asc_getTop: function () {
			return this.Top;
		}, asc_putTop: function (v) {
			this.Top = v;
		}, asc_getBottom: function () {
			return this.Bottom;
		}, asc_putBottom: function (v) {
			this.Bottom = v;
		}, asc_getRight: function () {
			return this.Right;
		}, asc_putRight: function (v) {
			this.Right = v;
		}
	};

	/** @constructor */
	function asc_CShapeProperty() {
		this.type = null; // custom
		this.fill = null;
		this.stroke = null;
		this.paddings = null;
		this.canFill = true;
		this.canChangeArrows = false;
		this.bFromChart = false;
		this.bFromImage = false;
		this.Locked = false;
		this.w = null;
		this.h = null;
		this.vert = null;
		this.verticalTextAlign = null;
		this.textArtProperties = null;
		this.lockAspect = null;
		this.title = null;
		this.description = null;

        this.columnNumber = null;
        this.columnSpace = null;
        this.signatureId = null;
	}

	asc_CShapeProperty.prototype = {
		constructor: asc_CShapeProperty,
		asc_getType: function () {
			return this.type;
		}, asc_putType: function (v) {
			this.type = v;
		}, asc_getFill: function () {
			return this.fill;
		}, asc_putFill: function (v) {
			this.fill = v;
		}, asc_getStroke: function () {
			return this.stroke;
		}, asc_putStroke: function (v) {
			this.stroke = v;
		}, asc_getPaddings: function () {
			return this.paddings;
		}, asc_putPaddings: function (v) {
			this.paddings = v;
		}, asc_getCanFill: function () {
			return this.canFill;
		}, asc_putCanFill: function (v) {
			this.canFill = v;
		}, asc_getCanChangeArrows: function () {
			return this.canChangeArrows;
		}, asc_setCanChangeArrows: function (v) {
			this.canChangeArrows = v;
		}, asc_getFromChart: function () {
			return this.bFromChart;
		}, asc_setFromChart: function (v) {
			this.bFromChart = v;
		}, asc_getLocked: function () {
			return this.Locked;
		}, asc_setLocked: function (v) {
			this.Locked = v;
		},

		asc_getWidth: function () {
			return this.w;
		}, asc_putWidth: function (v) {
			this.w = v;
		}, asc_getHeight: function () {
			return this.h;
		}, asc_putHeight: function (v) {
			this.h = v;
		}, asc_getVerticalTextAlign: function () {
			return this.verticalTextAlign;
		}, asc_putVerticalTextAlign: function (v) {
			this.verticalTextAlign = v;
		}, asc_getVert: function () {
			return this.vert;
		}, asc_putVert: function (v) {
			this.vert = v;
		}, asc_getTextArtProperties: function () {
			return this.textArtProperties;
		}, asc_putTextArtProperties: function (v) {
			this.textArtProperties = v;
		}, asc_getLockAspect: function () {
			return this.lockAspect
		}, asc_putLockAspect: function (v) {
			this.lockAspect = v;
		}, asc_getTitle: function () {
			return this.title;
		}, asc_putTitle: function (v) {
			this.title = v;
		}, asc_getDescription: function () {
			return this.description;
		}, asc_putDescription: function (v) {
			this.description = v;
		},

		asc_getColumnNumber: function(){
			return this.columnNumber;
		},

		asc_putColumnNumber: function(v){
			this.columnNumber = v;
		},

		asc_getColumnSpace: function(){
			return this.columnSpace;
		},

		asc_putColumnSpace: function(v){
			this.columnSpace = v;
		},

		asc_getSignatureId: function(){
			return this.signatureId;
		},

		asc_putSignatureId: function(v){
			this.signatureId = v;
		},

		asc_getFromImage: function(){
			return this.bFromImage;
		},

		asc_putFromImage: function(v){
			this.bFromImage = v;
		}
	};

	/** @constructor */
	function asc_TextArtProperties(obj) {
		if (obj) {
			this.Fill = obj.Fill;//asc_Fill
			this.Line = obj.Line;//asc_Stroke
			this.Form = obj.Form;//srting
			this.Style = obj.Style;//
		} else {
			this.Fill = undefined;
			this.Line = undefined;
			this.Form = undefined;
			this.Style = undefined;
		}
	}

	asc_TextArtProperties.prototype.asc_putFill = function (oAscFill) {
		this.Fill = oAscFill;
	};
	asc_TextArtProperties.prototype.asc_getFill = function () {
		return this.Fill;
	};
	asc_TextArtProperties.prototype.asc_putLine = function (oAscStroke) {
		this.Line = oAscStroke;
	};
	asc_TextArtProperties.prototype.asc_getLine = function () {
		return this.Line;
	};
	asc_TextArtProperties.prototype.asc_putForm = function (sForm) {
		this.Form = sForm;
	};
	asc_TextArtProperties.prototype.asc_getForm = function () {
		return this.Form;
	};
	asc_TextArtProperties.prototype.asc_putStyle = function (Style) {
		this.Style = Style;
	};
	asc_TextArtProperties.prototype.asc_getStyle = function () {
		return this.Style;
	};

	function CImagePositionH(obj) {
		if (obj) {
			this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? undefined : obj.RelativeFrom;
			this.UseAlign = ( undefined === obj.UseAlign     ) ? undefined : obj.UseAlign;
			this.Align = ( undefined === obj.Align        ) ? undefined : obj.Align;
			this.Value = ( undefined === obj.Value        ) ? undefined : obj.Value;
			this.Percent = ( undefined === obj.Percent      ) ? undefined : obj.Percent;
		} else {
			this.RelativeFrom = undefined;
			this.UseAlign = undefined;
			this.Align = undefined;
			this.Value = undefined;
			this.Percent = undefined;
		}
	}

	CImagePositionH.prototype.get_RelativeFrom = function () {
		return this.RelativeFrom;
	};
	CImagePositionH.prototype.put_RelativeFrom = function (v) {
		this.RelativeFrom = v;
	};
	CImagePositionH.prototype.get_UseAlign = function () {
		return this.UseAlign;
	};
	CImagePositionH.prototype.put_UseAlign = function (v) {
		this.UseAlign = v;
	};
	CImagePositionH.prototype.get_Align = function () {
		return this.Align;
	};
	CImagePositionH.prototype.put_Align = function (v) {
		this.Align = v;
	};
	CImagePositionH.prototype.get_Value = function () {
		return this.Value;
	};
	CImagePositionH.prototype.put_Value = function (v) {
		this.Value = v;
	};
	CImagePositionH.prototype.get_Percent = function () {
		return this.Percent
	};
	CImagePositionH.prototype.put_Percent = function (v) {
		this.Percent = v;
	};

	function CImagePositionV(obj) {
		if (obj) {
			this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? undefined : obj.RelativeFrom;
			this.UseAlign = ( undefined === obj.UseAlign     ) ? undefined : obj.UseAlign;
			this.Align = ( undefined === obj.Align        ) ? undefined : obj.Align;
			this.Value = ( undefined === obj.Value        ) ? undefined : obj.Value;
			this.Percent = ( undefined === obj.Percent      ) ? undefined : obj.Percent;
		} else {
			this.RelativeFrom = undefined;
			this.UseAlign = undefined;
			this.Align = undefined;
			this.Value = undefined;
			this.Percent = undefined;
		}
	}

	CImagePositionV.prototype.get_RelativeFrom = function () {
		return this.RelativeFrom;
	};
	CImagePositionV.prototype.put_RelativeFrom = function (v) {
		this.RelativeFrom = v;
	};
	CImagePositionV.prototype.get_UseAlign = function () {
		return this.UseAlign;
	};
	CImagePositionV.prototype.put_UseAlign = function (v) {
		this.UseAlign = v;
	};
	CImagePositionV.prototype.get_Align = function () {
		return this.Align;
	};
	CImagePositionV.prototype.put_Align = function (v) {
		this.Align = v;
	};
	CImagePositionV.prototype.get_Value = function () {
		return this.Value;
	};
	CImagePositionV.prototype.put_Value = function (v) {
		this.Value = v;
	};
	CImagePositionV.prototype.get_Percent = function () {
		return this.Percent
	};
	CImagePositionV.prototype.put_Percent = function (v) {
		this.Percent = v;
	};

	function CPosition(obj) {
		if (obj) {
			this.X = (undefined == obj.X) ? null : obj.X;
			this.Y = (undefined == obj.Y) ? null : obj.Y;
		} else {
			this.X = null;
			this.Y = null;
		}
	}

	CPosition.prototype.get_X = function () {
		return this.X;
	};
	CPosition.prototype.put_X = function (v) {
		this.X = v;
	};
	CPosition.prototype.get_Y = function () {
		return this.Y;
	};
	CPosition.prototype.put_Y = function (v) {
		this.Y = v;
	};

	/** @constructor */
	function asc_CImgProperty(obj) {

		if (obj) {
			this.CanBeFlow = (undefined != obj.CanBeFlow) ? obj.CanBeFlow : true;

			this.Width = (undefined != obj.Width        ) ? obj.Width : undefined;
			this.Height = (undefined != obj.Height       ) ? obj.Height : undefined;
			this.WrappingStyle = (undefined != obj.WrappingStyle) ? obj.WrappingStyle : undefined;
			this.Paddings = (undefined != obj.Paddings     ) ? new asc_CPaddings(obj.Paddings) : undefined;
			this.Position = (undefined != obj.Position     ) ? new CPosition(obj.Position) : undefined;
			this.AllowOverlap = (undefined != obj.AllowOverlap ) ? obj.AllowOverlap : undefined;
			this.PositionH = (undefined != obj.PositionH    ) ? new CImagePositionH(obj.PositionH) : undefined;
			this.PositionV = (undefined != obj.PositionV    ) ? new CImagePositionV(obj.PositionV) : undefined;

			this.SizeRelH = (undefined != obj.SizeRelH) ? new CImagePositionH(obj.SizeRelH) : undefined;
			this.SizeRelV = (undefined != obj.SizeRelV) ? new CImagePositionV(obj.SizeRelV) : undefined;

			this.Internal_Position = (undefined != obj.Internal_Position) ? obj.Internal_Position : null;

			this.ImageUrl = (undefined != obj.ImageUrl) ? obj.ImageUrl : null;
			this.Locked = (undefined != obj.Locked) ? obj.Locked : false;
			this.lockAspect = (undefined != obj.lockAspect) ? obj.lockAspect : false;


			this.ChartProperties = (undefined != obj.ChartProperties) ? obj.ChartProperties : null;
			this.ShapeProperties = (undefined != obj.ShapeProperties) ? obj.ShapeProperties : null;

			this.ChangeLevel = (undefined != obj.ChangeLevel) ? obj.ChangeLevel : null;
			this.Group = (obj.Group != undefined) ? obj.Group : null;

			this.fromGroup = obj.fromGroup != undefined ? obj.fromGroup : null;
			this.severalCharts = obj.severalCharts != undefined ? obj.severalCharts : false;
			this.severalChartTypes = obj.severalChartTypes != undefined ? obj.severalChartTypes : undefined;
			this.severalChartStyles = obj.severalChartStyles != undefined ? obj.severalChartStyles : undefined;
			this.verticalTextAlign = obj.verticalTextAlign != undefined ? obj.verticalTextAlign : undefined;
			this.vert = obj.vert != undefined ? obj.vert : undefined;

			//oleObjects
			this.pluginGuid = obj.pluginGuid !== undefined ? obj.pluginGuid : undefined;
			this.pluginData = obj.pluginData !== undefined ? obj.pluginData : undefined;
			this.oleWidth = obj.oleWidth != undefined ? obj.oleWidth : undefined;
			this.oleHeight = obj.oleHeight != undefined ? obj.oleHeight : undefined;

			this.title = obj.title != undefined ? obj.title : undefined;
			this.description = obj.description != undefined ? obj.description : undefined;

            this.columnNumber =  obj.columnNumber != undefined ? obj.columnNumber : undefined;
            this.columnSpace =  obj.columnSpace != undefined ? obj.columnSpace : undefined;

		} else {
			this.CanBeFlow = true;
			this.Width = undefined;
			this.Height = undefined;
			this.WrappingStyle = undefined;
			this.Paddings = undefined;
			this.Position = undefined;
			this.PositionH = undefined;
			this.PositionV = undefined;

			this.SizeRelH = undefined;
			this.SizeRelV = undefined;

			this.Internal_Position = null;
			this.ImageUrl = null;
			this.Locked = false;

			this.ChartProperties = null;
			this.ShapeProperties = null;
			this.ImageProperties = null;

			this.ChangeLevel = null;
			this.Group = null;
			this.fromGroup = null;
			this.severalCharts = false;
			this.severalChartTypes = undefined;
			this.severalChartStyles = undefined;
			this.verticalTextAlign = undefined;
			this.vert = undefined;

			//oleObjects
			this.pluginGuid = undefined;
			this.pluginData = undefined;

			this.oleWidth = undefined;
			this.oleHeight = undefined;
            this.title = undefined;
            this.description = undefined;

            this.columnNumber = undefined;
            this.columnSpace =  undefined;
		}
	}

	asc_CImgProperty.prototype = {
		constructor: asc_CImgProperty,
		asc_getChangeLevel: function () {
			return this.ChangeLevel;
		}, asc_putChangeLevel: function (v) {
			this.ChangeLevel = v;
		},

		asc_getCanBeFlow: function () {
			return this.CanBeFlow;
		}, asc_getWidth: function () {
			return this.Width;
		}, asc_putWidth: function (v) {
			this.Width = v;
		}, asc_getHeight: function () {
			return this.Height;
		}, asc_putHeight: function (v) {
			this.Height = v;
		}, asc_getWrappingStyle: function () {
			return this.WrappingStyle;
		}, asc_putWrappingStyle: function (v) {
			this.WrappingStyle = v;
		},

		// Возвращается объект класса Asc.asc_CPaddings
		asc_getPaddings: function () {
			return this.Paddings;
		}, // Аргумент объект класса Asc.asc_CPaddings
		asc_putPaddings: function (v) {
			this.Paddings = v;
		}, asc_getAllowOverlap: function () {
			return this.AllowOverlap;
		}, asc_putAllowOverlap: function (v) {
			this.AllowOverlap = v;
		}, // Возвращается объект класса CPosition
		asc_getPosition: function () {
			return this.Position;
		}, // Аргумент объект класса CPosition
		asc_putPosition: function (v) {
			this.Position = v;
		}, asc_getPositionH: function () {
			return this.PositionH;
		}, asc_putPositionH: function (v) {
			this.PositionH = v;
		}, asc_getPositionV: function () {
			return this.PositionV;
		}, asc_putPositionV: function (v) {
			this.PositionV = v;
		},

		asc_getSizeRelH: function () {
			return this.SizeRelH;
		},

		asc_putSizeRelH: function (v) {
			this.SizeRelH = v;
		},

		asc_getSizeRelV: function () {
			return this.SizeRelV;
		},

		asc_putSizeRelV: function (v) {
			this.SizeRelV = v;
		},

		asc_getValue_X: function (RelativeFrom) {
        if (null != this.Internal_Position) {
            return this.Internal_Position.Calculate_X_Value(RelativeFrom);
        }
			return 0;
		}, asc_getValue_Y: function (RelativeFrom) {
          if (null != this.Internal_Position) {
              return this.Internal_Position.Calculate_Y_Value(RelativeFrom);
          }
			return 0;
		},

		asc_getImageUrl: function () {
			return this.ImageUrl;
		}, asc_putImageUrl: function (v) {
			this.ImageUrl = v;
		}, asc_getGroup: function () {
			return this.Group;
		}, asc_putGroup: function (v) {
			this.Group = v;
		}, asc_getFromGroup: function () {
			return this.fromGroup;
		}, asc_putFromGroup: function (v) {
			this.fromGroup = v;
		},

		asc_getisChartProps: function () {
			return this.isChartProps;
		}, asc_putisChartPross: function (v) {
			this.isChartProps = v;
		},

		asc_getSeveralCharts: function () {
			return this.severalCharts;
		}, asc_putSeveralCharts: function (v) {
			this.severalCharts = v;
		}, asc_getSeveralChartTypes: function () {
			return this.severalChartTypes;
		}, asc_putSeveralChartTypes: function (v) {
			this.severalChartTypes = v;
		},

		asc_getSeveralChartStyles: function () {
			return this.severalChartStyles;
		}, asc_putSeveralChartStyles: function (v) {
			this.severalChartStyles = v;
		},

		asc_getVerticalTextAlign: function () {
			return this.verticalTextAlign;
		}, asc_putVerticalTextAlign: function (v) {
			this.verticalTextAlign = v;
		}, asc_getVert: function () {
			return this.vert;
		}, asc_putVert: function (v) {
			this.vert = v;
		},

		asc_getLocked: function () {
			return this.Locked;
		}, asc_getLockAspect: function () {
			return this.lockAspect;
		}, asc_putLockAspect: function (v) {
			this.lockAspect = v;
		}, asc_getChartProperties: function () {
			return this.ChartProperties;
		}, asc_putChartProperties: function (v) {
			this.ChartProperties = v;
		}, asc_getShapeProperties: function () {
			return this.ShapeProperties;
		}, asc_putShapeProperties: function (v) {
			this.ShapeProperties = v;
		},

		asc_getOriginSize: function (api) {
			if (window['AscFormat'].isRealNumber(this.oleWidth) && window['AscFormat'].isRealNumber(this.oleHeight)) {
				return new asc_CImageSize(this.oleWidth, this.oleHeight, true);
			}
			if(this.ImageUrl === null)
			{
				return new asc_CImageSize(50, 50, false);
			}
			var _section_select = api.WordControl.m_oLogicDocument.Get_PageSizesByDrawingObjects();
			var _page_width = AscCommon.Page_Width;
			var _page_height = AscCommon.Page_Height;
			var _page_x_left_margin = AscCommon.X_Left_Margin;
			var _page_y_top_margin = AscCommon.Y_Top_Margin;
			var _page_x_right_margin = AscCommon.X_Right_Margin;
			var _page_y_bottom_margin = AscCommon.Y_Bottom_Margin;

			if (_section_select) {
          if (_section_select.W) {
              _page_width = _section_select.W;
          }

          if (_section_select.H) {
              _page_height = _section_select.H;
          }
			}

			var _image = api.ImageLoader.map_image_index[AscCommon.getFullImageSrc2(this.ImageUrl)];
			if (_image != undefined && _image.Image != null && _image.Status == window['AscFonts'].ImageLoadStatus.Complete) {
				var _w = Math.max(1, _page_width - (_page_x_left_margin + _page_x_right_margin));
				var _h = Math.max(1, _page_height - (_page_y_top_margin + _page_y_bottom_margin));

				var bIsCorrect = false;
				if (_image.Image != null) {
					var __w = Math.max((_image.Image.width * AscCommon.g_dKoef_pix_to_mm), 1);
					var __h = Math.max((_image.Image.height * AscCommon.g_dKoef_pix_to_mm), 1);

					var dKoef = Math.max(__w / _w, __h / _h);
					if (dKoef > 1) {
						_w = Math.max(5, __w / dKoef);
						_h = Math.max(5, __h / dKoef);

						bIsCorrect = true;
					} else {
						_w = __w;
						_h = __h;
					}
				}

				return new asc_CImageSize(_w, _h, bIsCorrect);
			}
			return new asc_CImageSize(50, 50, false);
		},

		//oleObjects
		asc_getPluginGuid: function () {
			return this.pluginGuid;
		},

		asc_putPluginGuid: function (v) {
			this.pluginGuid = v;
		},

		asc_getPluginData: function () {
			return this.pluginData;
		},

		asc_putPluginData: function (v) {
			this.pluginData = v;
		},

		asc_getTitle: function(){
			return this.title;
		},

		asc_putTitle: function(v){
			this.title = v;
		},

		asc_getDescription: function(){
			return this.description;
		},

		asc_putDescription: function(v){
			this.description = v;
		},

		asc_getColumnNumber: function(){
			return this.columnNumber;
		},

		asc_putColumnNumber: function(v){
			this.columnNumber = v;
		},

		asc_getColumnSpace: function(){
			return this.columnSpace;
		},

		asc_putColumnSpace: function(v){
			this.columnSpace = v;
		},

		asc_getSignatureId : function() {
			if (this.ShapeProperties)
				return this.ShapeProperties.asc_getSignatureId();
			return undefined;
		}
	};

	/** @constructor */
	function asc_CSelectedObject(type, val) {
		this.Type = (undefined != type) ? type : null;
		this.Value = (undefined != val) ? val : null;
	}

	asc_CSelectedObject.prototype = {
		asc_getObjectType: function () {
			return this.Type;
		}, asc_getObjectValue: function () {
			return this.Value;
		}
	};

	/** @constructor */
	function asc_CShapeFill() {
		this.type = null;
		this.fill = null;
		this.transparent = null;
	}

	asc_CShapeFill.prototype = {
		asc_getType: function () {
			return this.type;
		}, asc_putType: function (v) {
			this.type = v;
		}, asc_getFill: function () {
			return this.fill;
		}, asc_putFill: function (v) {
			this.fill = v;
		}, asc_getTransparent: function () {
			return this.transparent;
		}, asc_putTransparent: function (v) {
			this.transparent = v;
		}, asc_CheckForseSet: function () {
			if (null != this.transparent) {
				return true;
			}
			if (null != this.fill && this.fill.Positions != null) {
				return true;
			}
			return false;
		}
	};

	/** @constructor */
	function asc_CFillBlip() {
		this.type = c_oAscFillBlipType.STRETCH;
		this.url = "";
		this.texture_id = null;
	}

	asc_CFillBlip.prototype = {
		asc_getType: function () {
			return this.type
		}, asc_putType: function (v) {
			this.type = v;
		}, asc_getUrl: function () {
			return this.url;
		}, asc_putUrl: function (v) {
			this.url = v;
		}, asc_getTextureId: function () {
			return this.texture_id;
		}, asc_putTextureId: function (v) {
			this.texture_id = v;
		}
	};

	/** @constructor */
	function asc_CFillHatch() {
		this.PatternType = undefined;
		this.fgClr = undefined;
		this.bgClr = undefined;
	}

	asc_CFillHatch.prototype = {
		asc_getPatternType: function () {
			return this.PatternType;
		}, asc_putPatternType: function (v) {
			this.PatternType = v;
		}, asc_getColorFg: function () {
			return this.fgClr;
		}, asc_putColorFg: function (v) {
			this.fgClr = v;
		}, asc_getColorBg: function () {
			return this.bgClr;
		}, asc_putColorBg: function (v) {
			this.bgClr = v;
		}
	};

	/** @constructor */
	function asc_CFillGrad() {
		this.Colors = undefined;
		this.Positions = undefined;
		this.GradType = 0;

		this.LinearAngle = undefined;
		this.LinearScale = true;

		this.PathType = 0;
	}

	asc_CFillGrad.prototype = {
		asc_getColors: function () {
			return this.Colors;
		}, asc_putColors: function (v) {
			this.Colors = v;
		}, asc_getPositions: function () {
			return this.Positions;
		}, asc_putPositions: function (v) {
			this.Positions = v;
		}, asc_getGradType: function () {
			return this.GradType;
		}, asc_putGradType: function (v) {
			this.GradType = v;
		}, asc_getLinearAngle: function () {
			return this.LinearAngle;
		}, asc_putLinearAngle: function (v) {
			this.LinearAngle = v;
		}, asc_getLinearScale: function () {
			return this.LinearScale;
		}, asc_putLinearScale: function (v) {
			this.LinearScale = v;
		}, asc_getPathType: function () {
			return this.PathType;
		}, asc_putPathType: function (v) {
			this.PathType = v;
		}
	};

	/** @constructor */
	function asc_CFillSolid() {
		this.color = new asc_CColor();
	}

	asc_CFillSolid.prototype = {
		asc_getColor: function () {
			return this.color
		}, asc_putColor: function (v) {
			this.color = v;
		}
	};

	/** @constructor */
	function asc_CStroke() {
		this.type = null;
		this.width = null;
		this.color = null;
		this.prstDash = null;

		this.LineJoin = null;
		this.LineCap = null;

		this.LineBeginStyle = null;
		this.LineBeginSize = null;

		this.LineEndStyle = null;
		this.LineEndSize = null;

		this.canChangeArrows = false;
	}

	asc_CStroke.prototype = {
		asc_getType: function () {
			return this.type;
		}, asc_putType: function (v) {
			this.type = v;
		}, asc_getWidth: function () {
			return this.width;
		}, asc_putWidth: function (v) {
			this.width = v;
		}, asc_getColor: function () {
			return this.color;
		}, asc_putColor: function (v) {
			this.color = v;
		},

		asc_getLinejoin: function () {
			return this.LineJoin;
		}, asc_putLinejoin: function (v) {
			this.LineJoin = v;
		}, asc_getLinecap: function () {
			return this.LineCap;
		}, asc_putLinecap: function (v) {
			this.LineCap = v;
		},

		asc_getLinebeginstyle: function () {
			return this.LineBeginStyle;
		}, asc_putLinebeginstyle: function (v) {
			this.LineBeginStyle = v;
		}, asc_getLinebeginsize: function () {
			return this.LineBeginSize;
		}, asc_putLinebeginsize: function (v) {
			this.LineBeginSize = v;
		}, asc_getLineendstyle: function () {
			return this.LineEndStyle;
		}, asc_putLineendstyle: function (v) {
			this.LineEndStyle = v;
		}, asc_getLineendsize: function () {
			return this.LineEndSize;
		}, asc_putLineendsize: function (v) {
			this.LineEndSize = v;
		},

		asc_getCanChangeArrows: function () {
			return this.canChangeArrows;
		},

		asc_putPrstDash: function (v) {
			this.prstDash = v;
		}, asc_getPrstDash: function () {
			return this.prstDash;
		}
	};

	// цвет. может быть трех типов:
	// c_oAscColor.COLOR_TYPE_SRGB		: value - не учитывается
	// c_oAscColor.COLOR_TYPE_PRST		: value - имя стандартного цвета (map_prst_color)
	// c_oAscColor.COLOR_TYPE_SCHEME	: value - тип цвета в схеме
	// c_oAscColor.COLOR_TYPE_SYS		: конвертируется в srgb
	function CAscColorScheme() {
		this.colors = [];
		this.name = "";
	}

	CAscColorScheme.prototype.get_colors = function () {
		return this.colors;
	};
	CAscColorScheme.prototype.get_name = function () {
		return this.name;
	};
	CAscColorScheme.prototype.get_dk1 = function () {
		return this.colors[0];
	};
	CAscColorScheme.prototype.get_lt1 = function () {
		return this.colors[1];
	};
	CAscColorScheme.prototype.get_dk2 = function () {
		return this.colors[2];
	};
	CAscColorScheme.prototype.get_lt2 = function () {
		return this.colors[3];
	};
	CAscColorScheme.prototype.get_accent1 = function () {
		return this.colors[4];
	};
	CAscColorScheme.prototype.get_accent2 = function () {
		return this.colors[5];
	};
	CAscColorScheme.prototype.get_accent3 = function () {
		return this.colors[6];
	};
	CAscColorScheme.prototype.get_accent4 = function () {
		return this.colors[7];
	};
	CAscColorScheme.prototype.get_accent5 = function () {
		return this.colors[8];
	};
	CAscColorScheme.prototype.get_accent6 = function () {
		return this.colors[9];
	};
	CAscColorScheme.prototype.get_hlink = function () {
		return this.colors[10];
	};
	CAscColorScheme.prototype.get_folHlink = function () {
		return this.colors[11];
	};

	//-----------------------------------------------------------------
	// События движения мыши
	//-----------------------------------------------------------------
	function CMouseMoveData(obj)
	{
		if (obj)
		{
			this.Type  = ( undefined != obj.Type ) ? obj.Type : c_oAscMouseMoveDataTypes.Common;
			this.X_abs = ( undefined != obj.X_abs ) ? obj.X_abs : 0;
			this.Y_abs = ( undefined != obj.Y_abs ) ? obj.Y_abs : 0;

			switch (this.Type)
			{
				case c_oAscMouseMoveDataTypes.Hyperlink :
				{
					this.Hyperlink = ( undefined != obj.PageNum ) ? obj.PageNum : 0;
					break;
				}

				case c_oAscMouseMoveDataTypes.LockedObject :
				{
					this.UserId           = ( undefined != obj.UserId ) ? obj.UserId : "";
					this.HaveChanges      = ( undefined != obj.HaveChanges ) ? obj.HaveChanges : false;
					this.LockedObjectType =
						( undefined != obj.LockedObjectType ) ? obj.LockedObjectType : Asc.c_oAscMouseMoveLockedObjectType.Common;
					break;
				}
				case c_oAscMouseMoveDataTypes.Footnote:
				{
					this.Text   = "";
					this.Number = 1;
					break;
				}
			}
		}
		else
		{
			this.Type  = c_oAscMouseMoveDataTypes.Common;
			this.X_abs = 0;
			this.Y_abs = 0;
		}
	}

	CMouseMoveData.prototype.get_Type = function () {
		return this.Type;
	};
	CMouseMoveData.prototype.get_X = function () {
		return this.X_abs;
	};
	CMouseMoveData.prototype.get_Y = function () {
		return this.Y_abs;
	};
	CMouseMoveData.prototype.get_Hyperlink = function () {
		return this.Hyperlink;
	};
	CMouseMoveData.prototype.get_UserId = function () {
		return this.UserId;
	};
	CMouseMoveData.prototype.get_HaveChanges = function () {
		return this.HaveChanges;
	};
	CMouseMoveData.prototype.get_LockedObjectType = function () {
		return this.LockedObjectType;
	};
	CMouseMoveData.prototype.get_FootnoteText = function()
	{
		return this.Text;
	};
	CMouseMoveData.prototype.get_FootnoteNumber = function()
	{
		return this.Number;
	};


	/**
	 * Класс для работы с интерфейсом для гиперссылок
	 * @param obj
	 * @constructor
	 */
    function CHyperlinkProperty(obj)
	{
		if (obj)
		{
			this.Text    = (undefined != obj.Text   ) ? obj.Text : null;
			this.Value   = (undefined != obj.Value  ) ? obj.Value : "";
			this.ToolTip = (undefined != obj.ToolTip) ? obj.ToolTip : "";
			this.Class   = (undefined !== obj.Class ) ? obj.Class : null;
			this.Anchor  = (undefined !== obj.Anchor) ? obj.Anchor : null;
			this.Heading = (obj.Heading ? obj.Heading : null);
		}
		else
		{
			this.Text    = null;
			this.Value   = "";
			this.ToolTip = "";
			this.Class   = null;
			this.Anchor  = null;
			this.Heading = null;
		}
	}
    CHyperlinkProperty.prototype.get_Value   = function()
    {
        return this.Value;
    };
    CHyperlinkProperty.prototype.put_Value   = function(v)
    {
        this.Value = v;
    };
    CHyperlinkProperty.prototype.get_ToolTip = function()
    {
        return this.ToolTip;
    };
    CHyperlinkProperty.prototype.put_ToolTip = function(v)
    {
        this.ToolTip = v ? v.slice(0, Asc.c_oAscMaxTooltipLength) : v;
    };
    CHyperlinkProperty.prototype.get_Text    = function()
    {
        return this.Text;
    };
    CHyperlinkProperty.prototype.put_Text    = function(v)
    {
        this.Text = v;
    };
    CHyperlinkProperty.prototype.put_InternalHyperlink = function(oClass)
    {
        this.Class = oClass;
    };
    CHyperlinkProperty.prototype.get_InternalHyperlink = function()
    {
        return this.Class;
    };
    CHyperlinkProperty.prototype.is_TopOfDocument = function()
	{
		return (this.Anchor === "_top");
	};
    CHyperlinkProperty.prototype.put_TopOfDocument = function()
	{
		this.Anchor = "_top";
	};
    CHyperlinkProperty.prototype.get_Bookmark = function()
	{
		return this.Anchor;
	};
    CHyperlinkProperty.prototype.put_Bookmark = function(sBookmark)
	{
		this.Anchor = sBookmark;
	};
	CHyperlinkProperty.prototype.is_Heading = function()
	{
		return (this.Heading instanceof AscCommonWord.Paragraph ? true : false)
	};
	CHyperlinkProperty.prototype.put_Heading = function(oParagraph)
	{
		this.Heading = oParagraph;
	};
	CHyperlinkProperty.prototype.get_Heading = function()
	{
		return this.Heading;
	};

	window['Asc']['CHyperlinkProperty'] = window['Asc'].CHyperlinkProperty = CHyperlinkProperty;
	CHyperlinkProperty.prototype['get_Value']             = CHyperlinkProperty.prototype.get_Value;
	CHyperlinkProperty.prototype['put_Value']             = CHyperlinkProperty.prototype.put_Value;
	CHyperlinkProperty.prototype['get_ToolTip']           = CHyperlinkProperty.prototype.get_ToolTip;
	CHyperlinkProperty.prototype['put_ToolTip']           = CHyperlinkProperty.prototype.put_ToolTip;
	CHyperlinkProperty.prototype['get_Text']              = CHyperlinkProperty.prototype.get_Text;
	CHyperlinkProperty.prototype['put_Text']              = CHyperlinkProperty.prototype.put_Text;
	CHyperlinkProperty.prototype['get_InternalHyperlink'] = CHyperlinkProperty.prototype.get_InternalHyperlink;
	CHyperlinkProperty.prototype['put_InternalHyperlink'] = CHyperlinkProperty.prototype.put_InternalHyperlink;
	CHyperlinkProperty.prototype['is_TopOfDocument']      = CHyperlinkProperty.prototype.is_TopOfDocument;
	CHyperlinkProperty.prototype['put_TopOfDocument']     = CHyperlinkProperty.prototype.put_TopOfDocument;
	CHyperlinkProperty.prototype['get_Bookmark']          = CHyperlinkProperty.prototype.get_Bookmark;
	CHyperlinkProperty.prototype['put_Bookmark']          = CHyperlinkProperty.prototype.put_Bookmark;
	CHyperlinkProperty.prototype['is_Heading']            = CHyperlinkProperty.prototype.is_Heading;
	CHyperlinkProperty.prototype['put_Heading']           = CHyperlinkProperty.prototype.put_Heading;
	CHyperlinkProperty.prototype['get_Heading']           = CHyperlinkProperty.prototype.get_Heading;


	/** @constructor */
	function asc_CUserInfo() {
		this.Id = null;
		this.FullName = null;
		this.FirstName = null;
		this.LastName = null;
	}

	asc_CUserInfo.prototype.asc_putId = asc_CUserInfo.prototype.put_Id = function (v) {
		this.Id = v;
	};
	asc_CUserInfo.prototype.asc_getId = asc_CUserInfo.prototype.get_Id = function () {
		return this.Id;
	};
	asc_CUserInfo.prototype.asc_putFullName = asc_CUserInfo.prototype.put_FullName = function (v) {
		this.FullName = v;
	};
	asc_CUserInfo.prototype.asc_getFullName = asc_CUserInfo.prototype.get_FullName = function () {
		return this.FullName;
	};
	asc_CUserInfo.prototype.asc_putFirstName = asc_CUserInfo.prototype.put_FirstName = function (v) {
		this.FirstName = v;
	};
	asc_CUserInfo.prototype.asc_getFirstName = asc_CUserInfo.prototype.get_FirstName = function () {
		return this.FirstName;
	};
	asc_CUserInfo.prototype.asc_putLastName = asc_CUserInfo.prototype.put_LastName = function (v) {
		this.LastName = v;
	};
	asc_CUserInfo.prototype.asc_getLastName = asc_CUserInfo.prototype.get_LastName = function () {
		return this.LastName;
	};

	/** @constructor */
	function asc_CDocInfo() {
		this.Id = null;
		this.Url = null;
		this.Title = null;
		this.Format = null;
		this.VKey = null;
		this.Token = null;
		this.UserInfo = null;
		this.Options = null;
		this.CallbackUrl = null;
		this.TemplateReplacement = null;
		this.Mode = null;
		this.Permissions = null;
		this.Lang = null;
		this.OfflineApp = false;
		this.Encrypted;
	}

	prot = asc_CDocInfo.prototype;
	prot.get_Id = prot.asc_getId = function () {
		return this.Id
	};
	prot.put_Id = prot.asc_putId = function (v) {
		this.Id = v;
	};
	prot.get_Url = prot.asc_getUrl = function () {
		return this.Url;
	};
	prot.put_Url = prot.asc_putUrl = function (v) {
		this.Url = v;
	};
	prot.get_Title = prot.asc_getTitle = function () {
		return this.Title;
	};
	prot.put_Title = prot.asc_putTitle = function (v) {
		this.Title = v;
	};
	prot.get_Format = prot.asc_getFormat = function () {
		return this.Format;
	};
	prot.put_Format = prot.asc_putFormat = function (v) {
		this.Format = v;
	};
	prot.get_VKey = prot.asc_getVKey = function () {
		return this.VKey;
	};
	prot.put_VKey = prot.asc_putVKey = function (v) {
		this.VKey = v;
	};
	prot.get_Token = prot.asc_getToken = function () {
		return this.Token;
	};
	prot.put_Token = prot.asc_putToken = function (v) {
		this.Token = v;
	};
	prot.get_OfflineApp = function () {
		return this.OfflineApp;
	};
	prot.put_OfflineApp = function (v) {
		this.OfflineApp = v;
	};
	prot.get_UserId = prot.asc_getUserId = function () {
		return (this.UserInfo ? this.UserInfo.get_Id() : null );
	};
	prot.get_UserName = prot.asc_getUserName = function () {
		return (this.UserInfo ? this.UserInfo.get_FullName() : null );
	};
	prot.get_FirstName = prot.asc_getFirstName = function () {
		return (this.UserInfo ? this.UserInfo.get_FirstName() : null );
	};
	prot.get_LastName = prot.asc_getLastName = function () {
		return (this.UserInfo ? this.UserInfo.get_LastName() : null );
	};
	prot.get_Options = prot.asc_getOptions = function () {
		return this.Options;
	};
	prot.put_Options = prot.asc_putOptions = function (v) {
		this.Options = v;
	};
	prot.get_CallbackUrl = prot.asc_getCallbackUrl = function () {
		return this.CallbackUrl;
	};
	prot.put_CallbackUrl = prot.asc_putCallbackUrl = function (v) {
		this.CallbackUrl = v;
	};
	prot.get_TemplateReplacement = prot.asc_getTemplateReplacement = function () {
		return this.TemplateReplacement;
	};
	prot.put_TemplateReplacement = prot.asc_putTemplateReplacement = function (v) {
		this.TemplateReplacement = v;
	};
	prot.get_UserInfo = prot.asc_getUserInfo = function () {
		return this.UserInfo;
	};
	prot.put_UserInfo = prot.asc_putUserInfo = function (v) {
		this.UserInfo = v;
	};
	prot.get_Mode = prot.asc_getMode = function () {
		return this.Mode;
	};
	prot.put_Mode = prot.asc_putMode = function (v) {
		this.Mode = v;
	};
	prot.get_Permissions = prot.asc_getPermissions = function () {
		return this.Permissions;
	};
	prot.put_Permissions = prot.asc_putPermissions = function (v) {
		this.Permissions = v;
	};
	prot.get_Lang = prot.asc_getLang = function () {
		return this.Lang;
	};
	prot.put_Lang = prot.asc_putLang = function (v) {
		this.Lang = v;
	};
	prot.get_Encrypted = prot.asc_getEncrypted = function () {
		return this.Encrypted;
	};
	prot.put_Encrypted = prot.asc_putEncrypted = function (v) {
		this.Encrypted = v;
	};

	function COpenProgress() {
		this.Type = Asc.c_oAscAsyncAction.Open;

		this.FontsCount = 0;
		this.CurrentFont = 0;

		this.ImagesCount = 0;
		this.CurrentImage = 0;
	}

	COpenProgress.prototype.asc_getType = function () {
		return this.Type
	};
	COpenProgress.prototype.asc_getFontsCount = function () {
		return this.FontsCount
	};
	COpenProgress.prototype.asc_getCurrentFont = function () {
		return this.CurrentFont
	};
	COpenProgress.prototype.asc_getImagesCount = function () {
		return this.ImagesCount
	};
	COpenProgress.prototype.asc_getCurrentImage = function () {
		return this.CurrentImage
	};

	function CErrorData() {
		this.Value = 0;
	}

	CErrorData.prototype.put_Value = function (v) {
		this.Value = v;
	};
	CErrorData.prototype.get_Value = function () {
		return this.Value;
	};

	function CAscMathType() {
		this.Id = 0;

		this.X = 0;
		this.Y = 0;
	}

	CAscMathType.prototype.get_Id = function () {
		return this.Id;
	};
	CAscMathType.prototype.get_X = function () {
		return this.X;
	};
	CAscMathType.prototype.get_Y = function () {
		return this.Y;
	};

	function CAscMathCategory() {
		this.Id = 0;
		this.Data = [];

		this.W = 0;
		this.H = 0;
	}

	CAscMathCategory.prototype.get_Id = function () {
		return this.Id;
	};
	CAscMathCategory.prototype.get_Data = function () {
		return this.Data;
	};
	CAscMathCategory.prototype.get_W = function () {
		return this.W;
	};
	CAscMathCategory.prototype.get_H = function () {
		return this.H;
	};
	CAscMathCategory.prototype.private_Sort = function () {
		this.Data.sort(function (a, b) {
			return a.Id - b.Id;
		});
	};

	function CStyleImage(name, type, image, uiPriority) {
		this.Name = name;
		this.type = type;
		this.image = image;
		this.uiPriority = uiPriority;
	}

	CStyleImage.prototype.asc_getName = CStyleImage.prototype.get_Name = function () {
		return this.Name;
	};
	CStyleImage.prototype.asc_getType = CStyleImage.prototype.get_Type = function () {
		return this.type;
	};
	CStyleImage.prototype.asc_getImage = function () {
		return this.image;
	};


	/** @constructor */
    function asc_CSpellCheckProperty(Word, Checked, Variants, ParaId, Element)
    {
        this.Word     = Word;
        this.Checked  = Checked;
        this.Variants = Variants;

        this.ParaId  = ParaId;
        this.Element = Element;
    }

    asc_CSpellCheckProperty.prototype.get_Word     = function()
    {
        return this.Word;
    };
    asc_CSpellCheckProperty.prototype.get_Checked  = function()
    {
        return this.Checked;
    };
    asc_CSpellCheckProperty.prototype.get_Variants = function()
    {
        return this.Variants;
    };

    function CWatermarkOnDraw(htmlContent)
	{
		// example content:
		/*
		{
			"type" : "rect",
			"width" : 100, // mm
			"height" : 100, // mm
			"rotate" : -45, // degrees
			"margins" : [ 10, 10, 10, 10 ], // text margins
			"fill" : [255, 0, 0], // [] => none
			"stroke-width" : 1, // mm
			"stroke" : [0, 0, 255], // [] => none
			"align" : 1, // vertical text align (4 - top, 1 - center, 0 - bottom)

			"paragraphs" : [
				{
					"align" : 4, // horizontal text align [1 - left, 2 - center, 0 - right, 3 - justify]
					"fill" : [255, 0, 0], // paragraph highlight. [] => none
					"linespacing" : 0,

					"runs" : [
						{
							"text" : "some text",
							"fill" : [255, 255, 255], // text highlight. [] => none,
							"font-family" : "Arial",
							"font-size" : 24, // pt
							"bold" : true,
							"italic" : false,
							"strikeout" : "false",
							"underline" : "false"
						},
						{
							"text" : "<%br%>"
						}
					]
				}
			]
		}
		*/

		this.inputContentSrc = htmlContent;
		this.replaceMap = {};

		this.image = null;
		this.imageBase64 = undefined;
		this.width = 0;
		this.height = 0;

		this.transparent = 0.3;
		this.zoom = 1;
		this.calculatezoom = -1;

		this.CheckParams = function(api)
		{
			this.replaceMap["%user_name%"] = api.User.userName;
		};

		this.Generate = function()
		{
			if (this.zoom == this.calculatezoom)
				return;

			this.calculatezoom = this.zoom;

			var content = this.inputContentSrc;
			for (var key in this.replaceMap)
			{
				if (!this.replaceMap.hasOwnProperty(key))
					continue;

				content = content.replace(new RegExp(key, 'g'), this.replaceMap[key]);
			}

			var _obj = {};
			try
			{
				var _objTmp = JSON.parse(content);
				_obj = _objTmp;
			}
			catch (err)
			{

			}

			this.transparent = (undefined == _obj['transparent']) ? 0.3 : _obj['transparent'];

			this.privateGenerateShape(_obj);

			//var _data = this.image.toDataURL("image/png");
			//console.log(_data);
		};

		this.Draw = function(context, dw_or_dx, dh_or_dy, dw, dh)
		{
			if (!this.image)
				return;

			var x = 0;
			var y = 0;

			if (undefined == dw)
			{
				x = (dw_or_dx - this.width) >> 1;
				y = (dh_or_dy - this.height) >> 1;
			}
			else
			{
				x = (dw_or_dx + ((dw - this.width) / 2)) >> 0;
				y = (dh_or_dy + ((dh - this.height) / 2)) >> 0;
			}
			var oldGlobalAlpha = context.globalAlpha;
			context.globalAlpha = this.transparent;
			context.drawImage(this.image, x, y);
			context.globalAlpha = oldGlobalAlpha;
		};

		this.StartRenderer = function()
		{
			var canvasTransparent = document.createElement("canvas");
			canvasTransparent.width = this.image.width;
			canvasTransparent.height = this.image.height;
			var ctx = canvasTransparent.getContext("2d");
			ctx.globalAlpha = this.transparent;
			ctx.drawImage(this.image, 0, 0);
			this.imageBase64 = canvasTransparent.toDataURL("image/png");
			canvasTransparent = null;
		};
		this.EndRenderer = function()
		{
			delete this.imageBase64;
			this.imageBase64 = undefined;
		};
		this.DrawOnRenderer = function(renderer, w, h)
		{
			var wMM = this.width * g_dKoef_pix_to_mm / this.zoom;
			var hMM = this.height * g_dKoef_pix_to_mm / this.zoom;
			var x = (w - wMM) / 2;
			var y = (h - hMM) / 2;

			renderer.UseOriginImageUrl = true;
			renderer.drawImage(this.imageBase64, x, y, wMM, hMM);
			renderer.UseOriginImageUrl = false;
		};

		this.privateGenerateShape = function(obj)
		{
			AscFormat.ExecuteNoHistory(function(obj) {

                var oShape = new AscFormat.CShape();
                var bWord = false;
                var oApi = Asc['editor'] || editor;
                if(!oApi){
                    return null;
                }
                switch(oApi.getEditorId()){
                    case AscCommon.c_oEditorId.Word:{
                        oShape.setWordShape(true);
                        bWord = true;
                        break;
                    }
                    case AscCommon.c_oEditorId.Presentation:{
                        oShape.setWordShape(false);
                        oShape.setParent(oApi.WordControl.m_oLogicDocument.Slides[oApi.WordControl.m_oLogicDocument.CurPage]);
                        break;
                    }
					case AscCommon.c_oEditorId.Spreadsheet:{
                        oShape.setWordShape(false);
                        oShape.setWorksheet(oApi.wb.getWorksheet().model);
						break;
					}
				}

                oShape.setBDeleted(false);
				oShape.spPr = new AscFormat.CSpPr();
				oShape.spPr.setParent(oShape);
				oShape.spPr.setXfrm(new AscFormat.CXfrm());
				oShape.spPr.xfrm.setParent(oShape.spPr);
				oShape.spPr.xfrm.setOffX(0);
				oShape.spPr.xfrm.setOffY(0);
				oShape.spPr.xfrm.setExtX(obj['width']);
				oShape.spPr.xfrm.setExtY(obj['height']);
				oShape.spPr.xfrm.setRot(AscFormat.normalizeRotate(obj['rotate'] ? (obj['rotate'] * Math.PI / 180) : 0));
				oShape.spPr.setGeometry(AscFormat.CreateGeometry(obj['type']));
				if(obj['fill'] && obj['fill'].length === 3){
					oShape.spPr.setFill(AscFormat.CreteSolidFillRGB(obj['fill'][0], obj['fill'][1], obj['fill'][2]));
				}
				if(AscFormat.isRealNumber(obj['stroke-width']) || Array.isArray(obj['stroke']) && obj['stroke'].length === 3){
					var oUnifill;
					if(Array.isArray(obj['stroke']) && obj['stroke'].length === 3){
						oUnifill = AscFormat.CreteSolidFillRGB(obj['stroke'][0], obj['stroke'][1], obj['stroke'][2]);
					}
					else{
						oUnifill = AscFormat.CreteSolidFillRGB(0, 0, 0);
					}
					oShape.spPr.setLn(AscFormat.CreatePenFromParams(oUnifill, undefined, undefined, undefined, undefined, AscFormat.isRealNumber(obj['stroke-width']) ? obj['stroke-width'] : 12700.0/36000.0))
				}

				if(bWord){
					oShape.createTextBoxContent();
				}
				else{
					oShape.createTextBody();
				}
				var align = obj['align'];
				if(undefined != align){
					oShape.setVerticalAlign(align);
				}

				if(Array.isArray(obj['margins']) && obj['margins'].length === 4){
					oShape.setPaddings({Left: obj['margins'][0], Top: obj['margins'][1], Right: obj['margins'][2], Bottom: obj['margins'][3]});
				}
				var oContent = oShape.getDocContent();
				var aParagraphsS = obj['paragraphs'];
				if(aParagraphsS.length > 0){
                    oContent.Content.length = 0;
				}
				for(var i = 0; i < aParagraphsS.length; ++i){
					var oCurParS = aParagraphsS[i];
					var oNewParagraph = new Paragraph(oContent.DrawingDocument, oContent, !bWord);
					if(AscFormat.isRealNumber(oCurParS['align'])){
						oNewParagraph.Set_Align(oCurParS['align'])
					}
					if(Array.isArray(oCurParS['fill']) && oCurParS['fill'].length === 3){
						var oShd = new CDocumentShd();
						oShd.Value = Asc.c_oAscShdClear;
						oShd.Color.r = oCurParS['fill'][0];
						oShd.Color.g = oCurParS['fill'][1];
						oShd.Color.b = oCurParS['fill'][2];
						oNewParagraph.Set_Shd(oShd, true);
					}
					if(AscFormat.isRealNumber(oCurParS['linespacing'])){
						oNewParagraph.Set_Spacing({Line: oCurParS['linespacing'], LineRule: Asc.linerule_Auto}, true);
					}
					var aRunsS = oCurParS['runs'];
					for(var j = 0; j < aRunsS.length; ++j){
						var oRunS = aRunsS[j];
						var oRun = new AscCommonWord.ParaRun(oNewParagraph, false);
						if(Array.isArray(oRunS['fill']) && oRunS['fill'].length === 3){
							oRun.Set_Unifill(AscFormat.CreteSolidFillRGB(oRunS['fill'][0], oRunS['fill'][1], oRunS['fill'][2]));
						}
						if(oRunS['font-family']){
							oRun.Set_RFonts_Ascii({Name : oRunS['font-family'], Index : -1});
							oRun.Set_RFonts_CS({Name : oRunS['font-family'], Index : -1});
							oRun.Set_RFonts_EastAsia({Name : oRunS['font-family'], Index : -1});
							oRun.Set_RFonts_HAnsi({Name : oRunS['font-family'], Index : -1});
						}
						if(oRunS['font-size']){
							oRun.Set_FontSize(oRunS['font-size']);
						}
						oRun.Set_Bold(oRunS['bold'] === true);
						oRun.Set_Italic(oRunS['italic'] === true);
						oRun.Set_Strikeout(oRunS['strikeout'] === true);
						oRun.Set_Underline(oRunS['underline'] === true);

						var sCustomText = oRunS['text'];
						if(sCustomText === "<%br%>"){
							oRun.AddToContent(0, new ParaNewLine(break_Line), false);
						}
						else{
							oRun.AddText(sCustomText);
						}

						oNewParagraph.Internal_Content_Add(i, oRun, false);
					}
					oContent.Internal_Content_Add(oContent.Content.length, oNewParagraph);
				}

				oShape.recalculate();
				if (oShape.bWordShape)
				{
					oShape.recalculateText();
				}

				var oldShowParaMarks;
				if (window.editor)
				{
					oldShowParaMarks = editor.ShowParaMarks;
					editor.ShowParaMarks = false;
				}

				AscCommon.IsShapeToImageConverter = true;
				var _bounds_cheker = new AscFormat.CSlideBoundsChecker();

				var w_mm = 210;
				var h_mm = 297;
				var w_px = AscCommon.AscBrowser.convertToRetinaValue(w_mm * g_dKoef_mm_to_pix * this.zoom, true);
				var h_px = AscCommon.AscBrowser.convertToRetinaValue(h_mm * g_dKoef_mm_to_pix * this.zoom, true);

				_bounds_cheker.init(w_px, h_px, w_mm, h_mm);
				_bounds_cheker.transform(1,0,0,1,0,0);

				_bounds_cheker.AutoCheckLineWidth = true;
				_bounds_cheker.CheckLineWidth(oShape);
				oShape.draw(_bounds_cheker, 0);
				_bounds_cheker.CorrectBounds2();

				var _need_pix_width     = _bounds_cheker.Bounds.max_x - _bounds_cheker.Bounds.min_x + 1;
				var _need_pix_height    = _bounds_cheker.Bounds.max_y - _bounds_cheker.Bounds.min_y + 1;

				if (_need_pix_width <= 0 || _need_pix_height <= 0)
					return;

				if (!this.image)
					this.image = document.createElement("canvas");

				this.image.width = _need_pix_width;
				this.image.height = _need_pix_height;
				this.width = _need_pix_width;
				this.height = _need_pix_height;

				var _ctx = this.image.getContext('2d');

				var g = new AscCommon.CGraphics();
				g.init(_ctx, w_px, h_px, w_mm, h_mm);
				g.m_oFontManager = AscCommon.g_fontManager;

				g.m_oCoordTransform.tx = -_bounds_cheker.Bounds.min_x;
				g.m_oCoordTransform.ty = -_bounds_cheker.Bounds.min_y;
				g.transform(1,0,0,1,0,0);

				oShape.draw(g, 0);

				AscCommon.IsShapeToImageConverter = false;

				if (window.editor)
				{
					window.editor.ShowParaMarks = oldShowParaMarks;
				}

			}, this, [obj]);
		};
	}
	window.TEST_WATERMARK_STRING = "\
	{\
		\"transparent\" : 0.3,\
		\"type\" : \"rect\",\
		\"width\" : 100,\
		\"height\" : 100,\
		\"rotate\" : -45,\
		\"margins\" : [ 10, 10, 10, 10 ],\
		\"fill\" : [255, 0, 0],\
		\"stroke-width\" : 1,\
		\"stroke\" : [0, 0, 255],\
		\"align\" : 1,\
		\
		\"paragraphs\" : [\
		{\
			\"align\" : 2,\
			\"fill\" : [255, 0, 0],\
			\"linespacing\" : 1,\
			\
			\"runs\" : [\
				{\
					\"text\" : \"Do not steal, %user_name%!\",\
					\"fill\" : [0, 0, 0],\
					\"font-family\" : \"Arial\",\
					\"font-size\" : 40,\
					\"bold\" : true,\
					\"italic\" : false,\
					\"strikeout\" : false,\
					\"underline\" : false\
				},\
				{\
					\"text\" : \"<%br%>\"\
				}\
			]\
		}\
	]\
	}";

	// ----------------------------- plugins ------------------------------- //
	function CPluginVariation()
	{
		this.description = "";
		this.url         = "";
		this.baseUrl     = "";
		this.index       = 0;     // сверху не выставляем. оттуда в каком порядке пришли - в таком порядке и работают

		this.icons          = ["1x", "2x"];
		this.isViewer       = false;
		this.EditorsSupport = ["word", "cell", "slide"];

		this.isVisual     = false;      // визуальный ли
		this.isModal      = false;      // модальное ли окно (используется только для визуального)
		this.isInsideMode = false;      // отрисовка не в окне а внутри редактора (в панели) (используется только для визуального немодального)
		this.isCustomWindow = false;	// ued only if this.isModal == true

		this.initDataType = EPluginDataType.none;
		this.initData     = "";

		this.isUpdateOleOnResize = false;

		this.buttons = [{"text" : "Ok", "primary" : true}, {"text" : "Cancel", "primary" : false}];

		this.size = undefined;
		this.initOnSelectionChanged = undefined;

		this.events = [];
		this.eventsMap = {};
	}

	CPluginVariation.prototype["get_Description"] = function()
	{
		return this.description;
	};
	CPluginVariation.prototype["set_Description"] = function(value)
	{
		this.description = value;
	};
	CPluginVariation.prototype["get_Url"]         = function()
	{
		return this.url;
	};
	CPluginVariation.prototype["set_Url"]         = function(value)
	{
		this.url = value;
	};

	CPluginVariation.prototype["get_Icons"] = function()
	{
		return this.icons;
	};
	CPluginVariation.prototype["set_Icons"] = function(value)
	{
		this.icons = value;
	};

	CPluginVariation.prototype["get_Viewer"]         = function()
	{
		return this.isViewer;
	};
	CPluginVariation.prototype["set_Viewer"]         = function(value)
	{
		this.isViewer = value;
	};
	CPluginVariation.prototype["get_EditorsSupport"] = function()
	{
		return this.EditorsSupport;
	};
	CPluginVariation.prototype["set_EditorsSupport"] = function(value)
	{
		this.EditorsSupport = value;
	};


	CPluginVariation.prototype["get_Visual"]     = function()
	{
		return this.isVisual;
	};
	CPluginVariation.prototype["set_Visual"]     = function(value)
	{
		this.isVisual = value;
	};
	CPluginVariation.prototype["get_Modal"]      = function()
	{
		return this.isModal;
	};
	CPluginVariation.prototype["set_Modal"]      = function(value)
	{
		this.isModal = value;
	};
	CPluginVariation.prototype["get_InsideMode"] = function()
	{
		return this.isInsideMode;
	};
	CPluginVariation.prototype["set_InsideMode"] = function(value)
	{
		this.isInsideMode = value;
	};
	CPluginVariation.prototype["get_CustomWindow"] = function()
	{
		return this.isCustomWindow;
	};
	CPluginVariation.prototype["set_CustomWindow"] = function(value)
	{
		this.isCustomWindow = value;
	};

	CPluginVariation.prototype["get_InitDataType"] = function()
	{
		return this.initDataType;
	};
	CPluginVariation.prototype["set_InitDataType"] = function(value)
	{
		this.initDataType = value;
	};
	CPluginVariation.prototype["get_InitData"]     = function()
	{
		return this.initData;
	};
	CPluginVariation.prototype["set_InitData"]     = function(value)
	{
		this.initData = value;
	};

	CPluginVariation.prototype["get_UpdateOleOnResize"] = function()
	{
		return this.isUpdateOleOnResize;
	};
	CPluginVariation.prototype["set_UpdateOleOnResize"] = function(value)
	{
		this.isUpdateOleOnResize = value;
	};
	CPluginVariation.prototype["get_Buttons"]           = function()
	{
		return this.buttons;
	};
	CPluginVariation.prototype["set_Buttons"]           = function(value)
	{
		this.buttons = value;
	};
	CPluginVariation.prototype["get_Size"]           = function()
	{
		return this.size;
	};
	CPluginVariation.prototype["set_Size"]           = function(value)
	{
		this.size = value;
	};
	CPluginVariation.prototype["get_InitOnSelectionChanged"]           = function()
	{
		return this.initOnSelectionChanged;
	};
	CPluginVariation.prototype["set_InitOnSelectionChanged"]           = function(value)
	{
		this.initOnSelectionChanged = value;
	};
    CPluginVariation.prototype["get_Events"]           = function()
    {
        return this.events;
    };
    CPluginVariation.prototype["set_Events"]           = function(value)
    {
    	if (!value)
    		return;

        this.events = value.slice(0, value.length);
        this.eventsMap = {};
        for (var i = 0; i < this.events.length; i++)
        	this.eventsMap[this.events[i]] = true;
    };

	CPluginVariation.prototype["serialize"]   = function()
	{
		var _object            = {};
		_object["description"] = this.description;
		_object["url"]         = this.url;
		_object["index"]       = this.index;

		_object["icons"]          = this.icons;
		_object["isViewer"]       = this.isViewer;
		_object["EditorsSupport"] = this.EditorsSupport;

		_object["isVisual"]     = this.isVisual;
		_object["isModal"]      = this.isModal;
		_object["isInsideMode"] = this.isInsideMode;
		_object["isCustomWindow"] = this.isCustomWindow;

		_object["initDataType"] = this.initDataType;
		_object["initData"]     = this.initData;

		_object["isUpdateOleOnResize"] = this.isUpdateOleOnResize;

		_object["buttons"] = this.buttons;

		_object["size"] = this.size;
		_object["initOnSelectionChanged"] = this.initOnSelectionChanged;

		return _object;
	};
	CPluginVariation.prototype["deserialize"] = function(_object)
	{
		this.description = (_object["description"] != null) ? _object["description"] : this.description;
		this.url         = (_object["url"] != null) ? _object["url"] : this.url;
		this.index       = (_object["index"] != null) ? _object["index"] : this.index;

		this.icons          = (_object["icons"] != null) ? _object["icons"] : this.icons;
		this.isViewer       = (_object["isViewer"] != null) ? _object["isViewer"] : this.isViewer;
		this.EditorsSupport = (_object["EditorsSupport"] != null) ? _object["EditorsSupport"] : this.EditorsSupport;

		this.isVisual     = (_object["isVisual"] != null) ? _object["isVisual"] : this.isVisual;
		this.isModal      = (_object["isModal"] != null) ? _object["isModal"] : this.isModal;
		this.isInsideMode = (_object["isInsideMode"] != null) ? _object["isInsideMode"] : this.isInsideMode;
		this.isCustomWindow = (_object["isCustomWindow"] != null) ? _object["isCustomWindow"] : this.isCustomWindow;

		this.initDataType = (_object["initDataType"] != null) ? _object["initDataType"] : this.initDataType;
		this.initData     = (_object["initData"] != null) ? _object["initData"] : this.initData;

		this.isUpdateOleOnResize = (_object["isUpdateOleOnResize"] != null) ? _object["isUpdateOleOnResize"] : this.isUpdateOleOnResize;

		this.buttons = (_object["buttons"] != null) ? _object["buttons"] : this.buttons;

		this.size = (_object["size"] != null) ? _object["size"] : this.size;
		this.initOnSelectionChanged = (_object["initOnSelectionChanged"] != null) ? _object["initOnSelectionChanged"] : this.initOnSelectionChanged;
	};

	function CPlugin()
	{
		this.name    = "";
		this.guid    = "";
		this.baseUrl = "";

		this.variations = [];
	}

	CPlugin.prototype["get_Name"]    = function()
	{
		return this.name;
	};
	CPlugin.prototype["set_Name"]    = function(value)
	{
		this.name = value;
	};
	CPlugin.prototype["get_Guid"]    = function()
	{
		return this.guid;
	};
	CPlugin.prototype["set_Guid"]    = function(value)
	{
		this.guid = value;
	};
	CPlugin.prototype["get_BaseUrl"] = function()
	{
		return this.baseUrl;
	};
	CPlugin.prototype["set_BaseUrl"] = function(value)
	{
		this.baseUrl = value;
	};

	CPlugin.prototype["get_Variations"] = function()
	{
		return this.variations;
	};
	CPlugin.prototype["set_Variations"] = function(value)
	{
		this.variations = value;
	};

	CPlugin.prototype["serialize"]   = function()
	{
		var _object           = {};
		_object["name"]       = this.name;
		_object["guid"]       = this.guid;
		_object["baseUrl"]    = this.baseUrl;
		_object["variations"] = [];
		for (var i = 0; i < this.variations.length; i++)
		{
			_object["variations"].push(this.variations[i].serialize());
		}
		return _object;
	};
	CPlugin.prototype["deserialize"] = function(_object)
	{
		this.name       = (_object["name"] != null) ? _object["name"] : this.name;
		this.guid       = (_object["guid"] != null) ? _object["guid"] : this.guid;
		this.baseUrl    = (_object["baseUrl"] != null) ? _object["baseUrl"] : this.baseUrl;
		this.variations = [];
		for (var i = 0; i < _object["variations"].length; i++)
		{
			var _variation = new CPluginVariation();
			_variation["deserialize"](_object["variations"][i]);
			this.variations.push(_variation);
		}
	};

    /*
     * Export
     * -----------------------------------------------------------------------------
     */
	window['AscCommon'] = window['AscCommon'] || {};
	window['Asc'] = window['Asc'] || {};

	window['Asc']['c_oAscArrUserColors'] = window['Asc'].c_oAscArrUserColors = c_oAscArrUserColors;

	window["AscCommon"].CreateAscColorCustom = CreateAscColorCustom;
	window["AscCommon"].CreateAscColor = CreateAscColor;
	window["AscCommon"].CreateGUID = CreateGUID;

	window['Asc']['c_oLicenseResult'] = window['Asc'].c_oLicenseResult = c_oLicenseResult;
	prot = c_oLicenseResult;
	prot['Error'] = prot.Error;
	prot['Expired'] = prot.Expired;
	prot['Success'] = prot.Success;
	prot['UnknownUser'] = prot.UnknownUser;
	prot['Connections'] = prot.Connections;
	prot['ExpiredTrial'] = prot.ExpiredTrial;
	prot['SuccessLimit'] = prot.SuccessLimit;
	prot['UsersCount'] = prot.UsersCount;
	prot['ConnectionsOS'] = prot.ConnectionsOS;
	prot['UsersCountOS'] = prot.UsersCountOS;

	window['Asc']['c_oRights'] = window['Asc'].c_oRights = c_oRights;
	prot = c_oRights;
	prot['None'] = prot.None;
	prot['Edit'] = prot.Edit;
	prot['Review'] = prot.Review;
	prot['Comment'] = prot.Comment;
	prot['View'] = prot.View;

	window['Asc']['c_oLicenseMode'] = window['Asc'].c_oLicenseMode = c_oLicenseMode;
	prot = c_oLicenseMode;
	prot['None'] = prot.None;
	prot['Trial'] = prot.Trial;
	prot['Developer'] = prot.Developer;

	window["Asc"]["EPluginDataType"] = window["Asc"].EPluginDataType = EPluginDataType;
	prot         = EPluginDataType;
	prot['none'] = prot.none;
	prot['text'] = prot.text;
	prot['ole']  = prot.ole;
	prot['html'] = prot.html;

	window["AscCommon"]["asc_CSignatureLine"] = window["AscCommon"].asc_CSignatureLine = asc_CSignatureLine;
	prot = asc_CSignatureLine.prototype;
	prot["asc_getId"] = prot.asc_getId;
	prot["asc_setId"] = prot.asc_setId;
	prot["asc_getGuid"] = prot.asc_getGuid;
	prot["asc_setGuid"] = prot.asc_setGuid;
	prot["asc_getSigner1"] = prot.asc_getSigner1;
	prot["asc_setSigner1"] = prot.asc_setSigner1;
	prot["asc_getSigner2"] = prot.asc_getSigner2;
	prot["asc_setSigner2"] = prot.asc_setSigner2;
	prot["asc_getEmail"] = prot.asc_getEmail;
	prot["asc_setEmail"] = prot.asc_setEmail;
	prot["asc_getInstructions"] = prot.asc_getInstructions;
	prot["asc_setInstructions"] = prot.asc_setInstructions;
	prot["asc_getShowDate"] = prot.asc_getShowDate;
	prot["asc_setShowDate"] = prot.asc_setShowDate;
	prot["asc_getValid"] = prot.asc_getValid;
	prot["asc_setValid"] = prot.asc_setValid;
	prot["asc_getDate"] = prot.asc_getDate;
	prot["asc_setDate"] = prot.asc_setDate;
	prot["asc_getVisible"] = prot.asc_getVisible;
	prot["asc_setVisible"] = prot.asc_setVisible;
	prot["asc_getRequested"] = prot.asc_getRequested;
	prot["asc_setRequested"] = prot.asc_setRequested;

	window["AscCommon"].asc_CAscEditorPermissions = asc_CAscEditorPermissions;
	prot = asc_CAscEditorPermissions.prototype;
	prot["asc_getLicenseType"] = prot.asc_getLicenseType;
	prot["asc_getCanCoAuthoring"] = prot.asc_getCanCoAuthoring;
	prot["asc_getCanReaderMode"] = prot.asc_getCanReaderMode;
	prot["asc_getCanBranding"] = prot.asc_getCanBranding;
	prot["asc_getIsAutosaveEnable"] = prot.asc_getIsAutosaveEnable;
	prot["asc_getAutosaveMinInterval"] = prot.asc_getAutosaveMinInterval;
	prot["asc_getIsAnalyticsEnable"] = prot.asc_getIsAnalyticsEnable;
	prot["asc_getIsLight"] = prot.asc_getIsLight;
	prot["asc_getLicenseMode"] = prot.asc_getLicenseMode;
	prot["asc_getRights"] = prot.asc_getRights;
	prot["asc_getBuildVersion"] = prot.asc_getBuildVersion;
	prot["asc_getBuildNumber"] = prot.asc_getBuildNumber;

	window["AscCommon"].asc_ValAxisSettings = asc_ValAxisSettings;
	prot = asc_ValAxisSettings.prototype;
	prot["putMinValRule"] = prot.putMinValRule;
	prot["putMinVal"] = prot.putMinVal;
	prot["putMaxValRule"] = prot.putMaxValRule;
	prot["putMaxVal"] = prot.putMaxVal;
	prot["putInvertValOrder"] = prot.putInvertValOrder;
	prot["putLogScale"] = prot.putLogScale;
	prot["putLogBase"] = prot.putLogBase;
	prot["putUnits"] = prot.putUnits;
	prot["putShowUnitsOnChart"] = prot.putShowUnitsOnChart;
	prot["putMajorTickMark"] = prot.putMajorTickMark;
	prot["putMinorTickMark"] = prot.putMinorTickMark;
	prot["putTickLabelsPos"] = prot.putTickLabelsPos;
	prot["putCrossesRule"] = prot.putCrossesRule;
	prot["putCrosses"] = prot.putCrosses;
	prot["putDispUnitsRule"] = prot.putDispUnitsRule;
	prot["getDispUnitsRule"] = prot.getDispUnitsRule;
	prot["putAxisType"] = prot.putAxisType;
	prot["getAxisType"] = prot.getAxisType;
	prot["getMinValRule"] = prot.getMinValRule;
	prot["getMinVal"] = prot.getMinVal;
	prot["getMaxValRule"] = prot.getMaxValRule;
	prot["getMaxVal"] = prot.getMaxVal;
	prot["getInvertValOrder"] = prot.getInvertValOrder;
	prot["getLogScale"] = prot.getLogScale;
	prot["getLogBase"] = prot.getLogBase;
	prot["getUnits"] = prot.getUnits;
	prot["getShowUnitsOnChart"] = prot.getShowUnitsOnChart;
	prot["getMajorTickMark"] = prot.getMajorTickMark;
	prot["getMinorTickMark"] = prot.getMinorTickMark;
	prot["getTickLabelsPos"] = prot.getTickLabelsPos;
	prot["getCrossesRule"] = prot.getCrossesRule;
	prot["getCrosses"] = prot.getCrosses;
	prot["setDefault"] = prot.setDefault;

	window["AscCommon"].asc_CatAxisSettings = asc_CatAxisSettings;
	prot = asc_CatAxisSettings.prototype;
	prot["putIntervalBetweenTick"] = prot.putIntervalBetweenTick;
	prot["putIntervalBetweenLabelsRule"] = prot.putIntervalBetweenLabelsRule;
	prot["putIntervalBetweenLabels"] = prot.putIntervalBetweenLabels;
	prot["putInvertCatOrder"] = prot.putInvertCatOrder;
	prot["putLabelsAxisDistance"] = prot.putLabelsAxisDistance;
	prot["putMajorTickMark"] = prot.putMajorTickMark;
	prot["putMinorTickMark"] = prot.putMinorTickMark;
	prot["putTickLabelsPos"] = prot.putTickLabelsPos;
	prot["putCrossesRule"] = prot.putCrossesRule;
	prot["putCrosses"] = prot.putCrosses;
	prot["putAxisType"] = prot.putAxisType;
	prot["putLabelsPosition"] = prot.putLabelsPosition;
	prot["putCrossMaxVal"] = prot.putCrossMaxVal;
	prot["putCrossMinVal"] = prot.putCrossMinVal;
	prot["getIntervalBetweenTick"] = prot.getIntervalBetweenTick;
	prot["getIntervalBetweenLabelsRule"] = prot.getIntervalBetweenLabelsRule;
	prot["getIntervalBetweenLabels"] = prot.getIntervalBetweenLabels;
	prot["getInvertCatOrder"] = prot.getInvertCatOrder;
	prot["getLabelsAxisDistance"] = prot.getLabelsAxisDistance;
	prot["getMajorTickMark"] = prot.getMajorTickMark;
	prot["getMinorTickMark"] = prot.getMinorTickMark;
	prot["getTickLabelsPos"] = prot.getTickLabelsPos;
	prot["getCrossesRule"] = prot.getCrossesRule;
	prot["getCrosses"] = prot.getCrosses;
	prot["getAxisType"] = prot.getAxisType;
	prot["getLabelsPosition"] = prot.getLabelsPosition;
	prot["getCrossMaxVal"] = prot.getCrossMaxVal;
	prot["getCrossMinVal"] = prot.getCrossMinVal;
	prot["setDefault"] = prot.setDefault;

	window["Asc"]["asc_ChartSettings"] = window["Asc"].asc_ChartSettings = asc_ChartSettings;
	prot = asc_ChartSettings.prototype;
	prot["putStyle"] = prot.putStyle;
	prot["putTitle"] = prot.putTitle;
	prot["putRowCols"] = prot.putRowCols;
	prot["putHorAxisLabel"] = prot.putHorAxisLabel;
	prot["putVertAxisLabel"] = prot.putVertAxisLabel;
	prot["putLegendPos"] = prot.putLegendPos;
	prot["putDataLabelsPos"] = prot.putDataLabelsPos;
	prot["putCatAx"] = prot.putCatAx;
	prot["putValAx"] = prot.putValAx;
	prot["getStyle"] = prot.getStyle;
	prot["getTitle"] = prot.getTitle;
	prot["getRowCols"] = prot.getRowCols;
	prot["getHorAxisLabel"] = prot.getHorAxisLabel;
	prot["getVertAxisLabel"] = prot.getVertAxisLabel;
	prot["getLegendPos"] = prot.getLegendPos;
	prot["getDataLabelsPos"] = prot.getDataLabelsPos;
	prot["getHorAx"] = prot.getHorAx;
	prot["getVertAx"] = prot.getVertAx;
	prot["getHorGridLines"] = prot.getHorGridLines;
	prot["putHorGridLines"] = prot.putHorGridLines;
	prot["getVertGridLines"] = prot.getVertGridLines;
	prot["putVertGridLines"] = prot.putVertGridLines;
	prot["getType"] = prot.getType;
	prot["putType"] = prot.putType;
	prot["putShowSerName"] = prot.putShowSerName;
	prot["getShowSerName"] = prot.getShowSerName;
	prot["putShowCatName"] = prot.putShowCatName;
	prot["getShowCatName"] = prot.getShowCatName;
	prot["putShowVal"] = prot.putShowVal;
	prot["getShowVal"] = prot.getShowVal;
	prot["putSeparator"] = prot.putSeparator;
	prot["getSeparator"] = prot.getSeparator;
	prot["putHorAxisProps"] = prot.putHorAxisProps;
	prot["getHorAxisProps"] = prot.getHorAxisProps;
	prot["putVertAxisProps"] = prot.putVertAxisProps;
	prot["getVertAxisProps"] = prot.getVertAxisProps;
	prot["putRange"] = prot.putRange;
	prot["getRange"] = prot.getRange;
	prot["putInColumns"] = prot.putInColumns;
	prot["getInColumns"] = prot.getInColumns;
	prot["putShowMarker"] = prot.putShowMarker;
	prot["getShowMarker"] = prot.getShowMarker;
	prot["putLine"] = prot.putLine;
	prot["getLine"] = prot.getLine;
	prot["putSmooth"] = prot.putSmooth;
	prot["getSmooth"] = prot.getSmooth;
	prot["changeType"] = prot.changeType;
	prot["putShowHorAxis"] = prot.putShowHorAxis;
	prot["getShowHorAxis"] = prot.getShowHorAxis;
	prot["putShowVerAxis"] = prot.putShowVerAxis;
	prot["getShowVerAxis"] = prot.getShowVerAxis;

	window["AscCommon"].asc_CRect = asc_CRect;
	prot = asc_CRect.prototype;
	prot["asc_getX"] = prot.asc_getX;
	prot["asc_getY"] = prot.asc_getY;
	prot["asc_getWidth"] = prot.asc_getWidth;
	prot["asc_getHeight"] = prot.asc_getHeight;

	window["AscCommon"].CColor = CColor;
	prot = CColor.prototype;
	prot["getR"] = prot.getR;
	prot["get_r"] = prot.get_r;
	prot["put_r"] = prot.put_r;
	prot["getG"] = prot.getG;
	prot["get_g"] = prot.get_g;
	prot["put_g"] = prot.put_g;
	prot["getB"] = prot.getB;
	prot["get_b"] = prot.get_b;
	prot["put_b"] = prot.put_b;
	prot["getA"] = prot.getA;
	prot["get_hex"] = prot.get_hex;

	window["Asc"]["asc_CColor"] = window["Asc"].asc_CColor = asc_CColor;
	prot = asc_CColor.prototype;
	prot["get_r"] = prot["asc_getR"] = prot.asc_getR;
	prot["put_r"] = prot["asc_putR"] = prot.asc_putR;
	prot["get_g"] = prot["asc_getG"] = prot.asc_getG;
	prot["put_g"] = prot["asc_putG"] = prot.asc_putG;
	prot["get_b"] = prot["asc_getB"] = prot.asc_getB;
	prot["put_b"] = prot["asc_putB"] = prot.asc_putB;
	prot["get_a"] = prot["asc_getA"] = prot.asc_getA;
	prot["put_a"] = prot["asc_putA"] = prot.asc_putA;
	prot["get_auto"] = prot["asc_getAuto"] = prot.asc_getAuto;
	prot["put_auto"] = prot["asc_putAuto"] = prot.asc_putAuto;
	prot["get_type"] = prot["asc_getType"] = prot.asc_getType;
	prot["put_type"] = prot["asc_putType"] = prot.asc_putType;
	prot["get_value"] = prot["asc_getValue"] = prot.asc_getValue;
	prot["put_value"] = prot["asc_putValue"] = prot.asc_putValue;
	prot["get_hex"] = prot["asc_getHex"] = prot.asc_getHex;
	prot["get_color"] = prot["asc_getColor"] = prot.asc_getColor;
	prot["get_hex"] = prot["asc_getHex"] = prot.asc_getHex;

	window["Asc"]["asc_CTextBorder"] = window["Asc"].asc_CTextBorder = asc_CTextBorder;
	prot = asc_CTextBorder.prototype;
	prot["get_Color"] = prot["asc_getColor"] = prot.asc_getColor;
	prot["put_Color"] = prot["asc_putColor"] = prot.asc_putColor;
	prot["get_Size"] = prot["asc_getSize"] = prot.asc_getSize;
	prot["put_Size"] = prot["asc_putSize"] = prot.asc_putSize;
	prot["get_Value"] = prot["asc_getValue"] = prot.asc_getValue;
	prot["put_Value"] = prot["asc_putValue"] = prot.asc_putValue;
	prot["get_Space"] = prot["asc_getSpace"] = prot.asc_getSpace;
	prot["put_Space"] = prot["asc_putSpace"] = prot.asc_putSpace;
	prot["get_ForSelectedCells"] = prot["asc_getForSelectedCells"] = prot.asc_getForSelectedCells;
	prot["put_ForSelectedCells"] = prot["asc_putForSelectedCells"] = prot.asc_putForSelectedCells;

	window["Asc"]["asc_CParagraphBorders"] = asc_CParagraphBorders;
	prot = asc_CParagraphBorders.prototype;
	prot["get_Left"] = prot["asc_getLeft"] = prot.asc_getLeft;
	prot["put_Left"] = prot["asc_putLeft"] = prot.asc_putLeft;
	prot["get_Top"] = prot["asc_getTop"] = prot.asc_getTop;
	prot["put_Top"] = prot["asc_putTop"] = prot.asc_putTop;
	prot["get_Right"] = prot["asc_getRight"] = prot.asc_getRight;
	prot["put_Right"] = prot["asc_putRight"] = prot.asc_putRight;
	prot["get_Bottom"] = prot["asc_getBottom"] = prot.asc_getBottom;
	prot["put_Bottom"] = prot["asc_putBottom"] = prot.asc_putBottom;
	prot["get_Between"] = prot["asc_getBetween"] = prot.asc_getBetween;
	prot["put_Between"] = prot["asc_putBetween"] = prot.asc_putBetween;

	window["AscCommon"].asc_CListType = asc_CListType;
	prot = asc_CListType.prototype;
	prot["get_ListType"] = prot["asc_getListType"] = prot.asc_getListType;
	prot["get_ListSubType"] = prot["asc_getListSubType"] = prot.asc_getListSubType;

	window["AscCommon"].asc_CTextFontFamily = asc_CTextFontFamily;
	prot = asc_CTextFontFamily.prototype;
	prot["get_Name"] = prot["asc_getName"] = prot.asc_getName;
	prot["get_Index"] = prot["asc_getIndex"] = prot.asc_getIndex;

	window["Asc"]["asc_CParagraphTab"] = window["Asc"].asc_CParagraphTab = asc_CParagraphTab;
	prot = asc_CParagraphTab.prototype;
	prot["get_Value"] = prot["asc_getValue"] = prot.asc_getValue;
	prot["put_Value"] = prot["asc_putValue"] = prot.asc_putValue;
	prot["get_Pos"] = prot["asc_getPos"] = prot.asc_getPos;
	prot["put_Pos"] = prot["asc_putPos"] = prot.asc_putPos;
	prot["get_Leader"] = prot["asc_getLeader"] = prot.asc_getLeader;
	prot["put_Leader"] = prot["asc_putLeader"] = prot.asc_putLeader;

	window["Asc"]["asc_CParagraphTabs"] = window["Asc"].asc_CParagraphTabs = asc_CParagraphTabs;
	prot = asc_CParagraphTabs.prototype;
	prot["get_Count"] = prot["asc_getCount"] = prot.asc_getCount;
	prot["get_Tab"] = prot["asc_getTab"] = prot.asc_getTab;
	prot["add_Tab"] = prot["asc_addTab"] = prot.asc_addTab;
	prot["clear"] = prot.clear = prot["asc_clear"] = prot.asc_clear;

	window["Asc"]["asc_CParagraphShd"] = window["Asc"].asc_CParagraphShd = asc_CParagraphShd;
	prot = asc_CParagraphShd.prototype;
	prot["get_Value"] = prot["asc_getValue"] = prot.asc_getValue;
	prot["put_Value"] = prot["asc_putValue"] = prot.asc_putValue;
	prot["get_Color"] = prot["asc_getColor"] = prot.asc_getColor;
	prot["put_Color"] = prot["asc_putColor"] = prot.asc_putColor;

	window["Asc"]["asc_CParagraphFrame"] = window["Asc"].asc_CParagraphFrame = asc_CParagraphFrame;
	prot = asc_CParagraphFrame.prototype;
	prot["asc_getDropCap"] = prot["get_DropCap"] = prot.asc_getDropCap;
	prot["asc_putDropCap"] = prot["put_DropCap"] = prot.asc_putDropCap;
	prot["asc_getH"] = prot["get_H"] = prot.asc_getH;
	prot["asc_putH"] = prot["put_H"] = prot.asc_putH;
	prot["asc_getHAnchor"] = prot["get_HAnchor"] = prot.asc_getHAnchor;
	prot["asc_putHAnchor"] = prot["put_HAnchor"] = prot.asc_putHAnchor;
	prot["asc_getHRule"] = prot["get_HRule"] = prot.asc_getHRule;
	prot["asc_putHRule"] = prot["put_HRule"] = prot.asc_putHRule;
	prot["asc_getHSpace"] = prot["get_HSpace"] = prot.asc_getHSpace;
	prot["asc_putHSpace"] = prot["put_HSpace"] = prot.asc_putHSpace;
	prot["asc_getLines"] = prot["get_Lines"] = prot.asc_getLines;
	prot["asc_putLines"] = prot["put_Lines"] = prot.asc_putLines;
	prot["asc_getVAnchor"] = prot["get_VAnchor"] = prot.asc_getVAnchor;
	prot["asc_putVAnchor"] = prot["put_VAnchor"] = prot.asc_putVAnchor;
	prot["asc_getVSpace"] = prot["get_VSpace"] = prot.asc_getVSpace;
	prot["asc_putVSpace"] = prot["put_VSpace"] = prot.asc_putVSpace;
	prot["asc_getW"] = prot["get_W"] = prot.asc_getW;
	prot["asc_putW"] = prot["put_W"] = prot.asc_putW;
	prot["asc_getWrap"] = prot["get_Wrap"] = prot.asc_getWrap;
	prot["asc_putWrap"] = prot["put_Wrap"] = prot.asc_putWrap;
	prot["asc_getX"] = prot["get_X"] = prot.asc_getX;
	prot["asc_putX"] = prot["put_X"] = prot.asc_putX;
	prot["asc_getXAlign"] = prot["get_XAlign"] = prot.asc_getXAlign;
	prot["asc_putXAlign"] = prot["put_XAlign"] = prot.asc_putXAlign;
	prot["asc_getY"] = prot["get_Y"] = prot.asc_getY;
	prot["asc_putY"] = prot["put_Y"] = prot.asc_putY;
	prot["asc_getYAlign"] = prot["get_YAlign"] = prot.asc_getYAlign;
	prot["asc_putYAlign"] = prot["put_YAlign"] = prot.asc_putYAlign;
	prot["asc_getBorders"] = prot["get_Borders"] = prot.asc_getBorders;
	prot["asc_putBorders"] = prot["put_Borders"] = prot.asc_putBorders;
	prot["asc_getShade"] = prot["get_Shade"] = prot.asc_getShade;
	prot["asc_putShade"] = prot["put_Shade"] = prot.asc_putShade;
	prot["asc_getFontFamily"] = prot["get_FontFamily"] = prot.asc_getFontFamily;
	prot["asc_putFontFamily"] = prot["put_FontFamily"] = prot.asc_putFontFamily;
	prot["asc_putFromDropCapMenu"] = prot["put_FromDropCapMenu"] = prot.asc_putFromDropCapMenu;

	window["AscCommon"].asc_CParagraphSpacing = asc_CParagraphSpacing;
	prot = asc_CParagraphSpacing.prototype;
	prot["get_Line"] = prot["asc_getLine"] = prot.asc_getLine;
	prot["get_LineRule"] = prot["asc_getLineRule"] = prot.asc_getLineRule;
	prot["get_Before"] = prot["asc_getBefore"] = prot.asc_getBefore;
	prot["get_After"] = prot["asc_getAfter"] = prot.asc_getAfter;

	window["Asc"]["asc_CParagraphInd"] = window["Asc"].asc_CParagraphInd = asc_CParagraphInd;
	prot = asc_CParagraphInd.prototype;
	prot["get_Left"] = prot["asc_getLeft"] = prot.asc_getLeft;
	prot["put_Left"] = prot["asc_putLeft"] = prot.asc_putLeft;
	prot["get_Right"] = prot["asc_getRight"] = prot.asc_getRight;
	prot["put_Right"] = prot["asc_putRight"] = prot.asc_putRight;
	prot["get_FirstLine"] = prot["asc_getFirstLine"] = prot.asc_getFirstLine;
	prot["put_FirstLine"] = prot["asc_putFirstLine"] = prot.asc_putFirstLine;

	window["Asc"]["asc_CParagraphProperty"] = window["Asc"].asc_CParagraphProperty = asc_CParagraphProperty;
	prot = asc_CParagraphProperty.prototype;
	prot["get_ContextualSpacing"] = prot["asc_getContextualSpacing"] = prot.asc_getContextualSpacing;
	prot["put_ContextualSpacing"] = prot["asc_putContextualSpacing"] = prot.asc_putContextualSpacing;
	prot["get_Ind"] = prot["asc_getInd"] = prot.asc_getInd;
	prot["put_Ind"] = prot["asc_putInd"] = prot.asc_putInd;
	prot["get_KeepLines"] = prot["asc_getKeepLines"] = prot.asc_getKeepLines;
	prot["put_KeepLines"] = prot["asc_putKeepLines"] = prot.asc_putKeepLines;
	prot["get_KeepNext"] = prot["asc_getKeepNext"] = prot.asc_getKeepNext;
	prot["put_KeepNext"] = prot["asc_putKeepNext"] = prot.asc_putKeepNext;
	prot["get_PageBreakBefore"] = prot["asc_getPageBreakBefore"] = prot.asc_getPageBreakBefore;
	prot["put_PageBreakBefore"] = prot["asc_putPageBreakBefore"] = prot.asc_putPageBreakBefore;
	prot["get_WidowControl"] = prot["asc_getWidowControl"] = prot.asc_getWidowControl;
	prot["put_WidowControl"] = prot["asc_putWidowControl"] = prot.asc_putWidowControl;
	prot["get_Spacing"] = prot["asc_getSpacing"] = prot.asc_getSpacing;
	prot["put_Spacing"] = prot["asc_putSpacing"] = prot.asc_putSpacing;
	prot["get_Borders"] = prot["asc_getBorders"] = prot.asc_getBorders;
	prot["put_Borders"] = prot["asc_putBorders"] = prot.asc_putBorders;
	prot["get_Shade"] = prot["asc_getShade"] = prot.asc_getShade;
	prot["put_Shade"] = prot["asc_putShade"] = prot.asc_putShade;
	prot["get_Locked"] = prot["asc_getLocked"] = prot.asc_getLocked;
	prot["get_CanAddTable"] = prot["asc_getCanAddTable"] = prot.asc_getCanAddTable;
	prot["get_Subscript"] = prot["asc_getSubscript"] = prot.asc_getSubscript;
	prot["put_Subscript"] = prot["asc_putSubscript"] = prot.asc_putSubscript;
	prot["get_Superscript"] = prot["asc_getSuperscript"] = prot.asc_getSuperscript;
	prot["put_Superscript"] = prot["asc_putSuperscript"] = prot.asc_putSuperscript;
	prot["get_SmallCaps"] = prot["asc_getSmallCaps"] = prot.asc_getSmallCaps;
	prot["put_SmallCaps"] = prot["asc_putSmallCaps"] = prot.asc_putSmallCaps;
	prot["get_AllCaps"] = prot["asc_getAllCaps"] = prot.asc_getAllCaps;
	prot["put_AllCaps"] = prot["asc_putAllCaps"] = prot.asc_putAllCaps;
	prot["get_Strikeout"] = prot["asc_getStrikeout"] = prot.asc_getStrikeout;
	prot["put_Strikeout"] = prot["asc_putStrikeout"] = prot.asc_putStrikeout;
	prot["get_DStrikeout"] = prot["asc_getDStrikeout"] = prot.asc_getDStrikeout;
	prot["put_DStrikeout"] = prot["asc_putDStrikeout"] = prot.asc_putDStrikeout;
	prot["get_TextSpacing"] = prot["asc_getTextSpacing"] = prot.asc_getTextSpacing;
	prot["put_TextSpacing"] = prot["asc_putTextSpacing"] = prot.asc_putTextSpacing;
	prot["get_Position"] = prot["asc_getPosition"] = prot.asc_getPosition;
	prot["put_Position"] = prot["asc_putPosition"] = prot.asc_putPosition;
	prot["get_Tabs"] = prot["asc_getTabs"] = prot.asc_getTabs;
	prot["put_Tabs"] = prot["asc_putTabs"] = prot.asc_putTabs;
	prot["get_DefaultTab"] = prot["asc_getDefaultTab"] = prot.asc_getDefaultTab;
	prot["put_DefaultTab"] = prot["asc_putDefaultTab"] = prot.asc_putDefaultTab;
	prot["get_FramePr"] = prot["asc_getFramePr"] = prot.asc_getFramePr;
	prot["put_FramePr"] = prot["asc_putFramePr"] = prot.asc_putFramePr;
	prot["get_CanAddDropCap"] = prot["asc_getCanAddDropCap"] = prot.asc_getCanAddDropCap;
	prot["get_CanAddImage"] = prot["asc_getCanAddImage"] = prot.asc_getCanAddImage;

	window["AscCommon"].asc_CTexture = asc_CTexture;
	prot = asc_CTexture.prototype;
	prot["get_id"] = prot["asc_getId"] = prot.asc_getId;
	prot["get_image"] = prot["asc_getImage"] = prot.asc_getImage;

	window["AscCommon"].asc_CImageSize = asc_CImageSize;
	prot = asc_CImageSize.prototype;
	prot["get_ImageWidth"] = prot["asc_getImageWidth"] = prot.asc_getImageWidth;
	prot["get_ImageHeight"] = prot["asc_getImageHeight"] = prot.asc_getImageHeight;
	prot["get_IsCorrect"] = prot["asc_getIsCorrect"] = prot.asc_getIsCorrect;

	window["Asc"]["asc_CPaddings"] = window["Asc"].asc_CPaddings = asc_CPaddings;
	prot = asc_CPaddings.prototype;
	prot["get_Left"] = prot["asc_getLeft"] = prot.asc_getLeft;
	prot["put_Left"] = prot["asc_putLeft"] = prot.asc_putLeft;
	prot["get_Top"] = prot["asc_getTop"] = prot.asc_getTop;
	prot["put_Top"] = prot["asc_putTop"] = prot.asc_putTop;
	prot["get_Bottom"] = prot["asc_getBottom"] = prot.asc_getBottom;
	prot["put_Bottom"] = prot["asc_putBottom"] = prot.asc_putBottom;
	prot["get_Right"] = prot["asc_getRight"] = prot.asc_getRight;
	prot["put_Right"] = prot["asc_putRight"] = prot.asc_putRight;

	window["Asc"]["asc_CShapeProperty"] = window["Asc"].asc_CShapeProperty = asc_CShapeProperty;
	prot = asc_CShapeProperty.prototype;
	prot["get_type"] = prot["asc_getType"] = prot.asc_getType;
	prot["put_type"] = prot["asc_putType"] = prot.asc_putType;
	prot["get_fill"] = prot["asc_getFill"] = prot.asc_getFill;
	prot["put_fill"] = prot["asc_putFill"] = prot.asc_putFill;
	prot["get_stroke"] = prot["asc_getStroke"] = prot.asc_getStroke;
	prot["put_stroke"] = prot["asc_putStroke"] = prot.asc_putStroke;
	prot["get_paddings"] = prot["asc_getPaddings"] = prot.asc_getPaddings;
	prot["put_paddings"] = prot["asc_putPaddings"] = prot.asc_putPaddings;
	prot["get_CanFill"] = prot["asc_getCanFill"] = prot.asc_getCanFill;
	prot["put_CanFill"] = prot["asc_putCanFill"] = prot.asc_putCanFill;
	prot["get_CanChangeArrows"] = prot["asc_getCanChangeArrows"] = prot.asc_getCanChangeArrows;
	prot["set_CanChangeArrows"] = prot["asc_setCanChangeArrows"] = prot.asc_setCanChangeArrows;
	prot["get_FromChart"] = prot["asc_getFromChart"] = prot.asc_getFromChart;
	prot["set_FromChart"] = prot["asc_setFromChart"] = prot.asc_setFromChart;
	prot["get_Locked"] = prot["asc_getLocked"] = prot.asc_getLocked;
	prot["set_Locked"] = prot["asc_setLocked"] = prot.asc_setLocked;
	prot["get_Width"] = prot["asc_getWidth"] = prot.asc_getWidth;
	prot["put_Width"] = prot["asc_putWidth"] = prot.asc_putWidth;
	prot["get_Height"] = prot["asc_getHeight"] = prot.asc_getHeight;
	prot["put_Height"] = prot["asc_putHeight"] = prot.asc_putHeight;
	prot["get_VerticalTextAlign"] = prot["asc_getVerticalTextAlign"] = prot.asc_getVerticalTextAlign;
	prot["put_VerticalTextAlign"] = prot["asc_putVerticalTextAlign"] = prot.asc_putVerticalTextAlign;
	prot["get_Vert"] = prot["asc_getVert"] = prot.asc_getVert;
	prot["put_Vert"] = prot["asc_putVert"] = prot.asc_putVert;
	prot["get_TextArtProperties"] = prot["asc_getTextArtProperties"] = prot.asc_getTextArtProperties;
	prot["put_TextArtProperties"] = prot["asc_putTextArtProperties"] = prot.asc_putTextArtProperties;
	prot["get_LockAspect"] = prot["asc_getLockAspect"] = prot.asc_getLockAspect;
	prot["put_LockAspect"] = prot["asc_putLockAspect"] = prot.asc_putLockAspect;
	prot["get_Title"] = prot["asc_getTitle"] = prot.asc_getTitle;
	prot["put_Title"] = prot["asc_putTitle"] = prot.asc_putTitle;
	prot["get_Description"] = prot["asc_getDescription"] = prot.asc_getDescription;
	prot["put_Description"] = prot["asc_putDescription"] = prot.asc_putDescription;
	prot["get_ColumnNumber"] = prot["asc_getColumnNumber"] = prot.asc_getColumnNumber;
	prot["put_ColumnNumber"] = prot["asc_putColumnNumber"] = prot.asc_putColumnNumber;
	prot["get_ColumnSpace"] = prot["asc_getColumnSpace"] = prot.asc_getColumnSpace;
	prot["put_ColumnSpace"] = prot["asc_putColumnSpace"] = prot.asc_putColumnSpace;
	prot["get_SignatureId"] = prot["asc_getSignatureId"] = prot.asc_getSignatureId;
	prot["put_SignatureId"] = prot["asc_putSignatureId"] = prot.asc_putSignatureId;
	prot["get_FromImage"] = prot["asc_getFromImage"] = prot.asc_getFromImage;
	prot["put_FromImage"] = prot["asc_putFromImage"] = prot.asc_putFromImage;

	window["Asc"]["asc_TextArtProperties"] = window["Asc"].asc_TextArtProperties = asc_TextArtProperties;
	prot = asc_TextArtProperties.prototype;
	prot["asc_putFill"] = prot.asc_putFill;
	prot["asc_getFill"] = prot.asc_getFill;
	prot["asc_putLine"] = prot.asc_putLine;
	prot["asc_getLine"] = prot.asc_getLine;
	prot["asc_putForm"] = prot.asc_putForm;
	prot["asc_getForm"] = prot.asc_getForm;
	prot["asc_putStyle"] = prot.asc_putStyle;
	prot["asc_getStyle"] = prot.asc_getStyle;

	window['Asc']['CImagePositionH'] = window["Asc"].CImagePositionH = CImagePositionH;
	prot = CImagePositionH.prototype;
	prot['get_RelativeFrom'] = prot.get_RelativeFrom;
	prot['put_RelativeFrom'] = prot.put_RelativeFrom;
	prot['get_UseAlign'] = prot.get_UseAlign;
	prot['put_UseAlign'] = prot.put_UseAlign;
	prot['get_Align'] = prot.get_Align;
	prot['put_Align'] = prot.put_Align;
	prot['get_Value'] = prot.get_Value;
	prot['put_Value'] = prot.put_Value;
	prot['get_Percent'] = prot.get_Percent;
	prot['put_Percent'] = prot.put_Percent;

	window['Asc']['CImagePositionV'] = window["Asc"].CImagePositionV = CImagePositionV;
	prot = CImagePositionV.prototype;
	prot['get_RelativeFrom'] = prot.get_RelativeFrom;
	prot['put_RelativeFrom'] = prot.put_RelativeFrom;
	prot['get_UseAlign'] = prot.get_UseAlign;
	prot['put_UseAlign'] = prot.put_UseAlign;
	prot['get_Align'] = prot.get_Align;
	prot['put_Align'] = prot.put_Align;
	prot['get_Value'] = prot.get_Value;
	prot['put_Value'] = prot.put_Value;
	prot['get_Percent'] = prot.get_Percent;
	prot['put_Percent'] = prot.put_Percent;

	window['Asc']['CPosition'] = window["Asc"].CPosition = CPosition;
	prot = CPosition.prototype;
	prot['get_X'] = prot.get_X;
	prot['put_X'] = prot.put_X;
	prot['get_Y'] = prot.get_Y;
	prot['put_Y'] = prot.put_Y;

	window["Asc"]["asc_CImgProperty"] = window["Asc"].asc_CImgProperty = asc_CImgProperty;
	prot = asc_CImgProperty.prototype;
	prot["get_ChangeLevel"] = prot["asc_getChangeLevel"] = prot.asc_getChangeLevel;
	prot["put_ChangeLevel"] = prot["asc_putChangeLevel"] = prot.asc_putChangeLevel;
	prot["get_CanBeFlow"] = prot["asc_getCanBeFlow"] = prot.asc_getCanBeFlow;
	prot["get_Width"] = prot["asc_getWidth"] = prot.asc_getWidth;
	prot["put_Width"] = prot["asc_putWidth"] = prot.asc_putWidth;
	prot["get_Height"] = prot["asc_getHeight"] = prot.asc_getHeight;
	prot["put_Height"] = prot["asc_putHeight"] = prot.asc_putHeight;
	prot["get_WrappingStyle"] = prot["asc_getWrappingStyle"] = prot.asc_getWrappingStyle;
	prot["put_WrappingStyle"] = prot["asc_putWrappingStyle"] = prot.asc_putWrappingStyle;
	prot["get_Paddings"] = prot["asc_getPaddings"] = prot.asc_getPaddings;
	prot["put_Paddings"] = prot["asc_putPaddings"] = prot.asc_putPaddings;
	prot["get_AllowOverlap"] = prot["asc_getAllowOverlap"] = prot.asc_getAllowOverlap;
	prot["put_AllowOverlap"] = prot["asc_putAllowOverlap"] = prot.asc_putAllowOverlap;
	prot["get_Position"] = prot["asc_getPosition"] = prot.asc_getPosition;
	prot["put_Position"] = prot["asc_putPosition"] = prot.asc_putPosition;
	prot["get_PositionH"] = prot["asc_getPositionH"] = prot.asc_getPositionH;
	prot["put_PositionH"] = prot["asc_putPositionH"] = prot.asc_putPositionH;
	prot["get_PositionV"] = prot["asc_getPositionV"] = prot.asc_getPositionV;
	prot["put_PositionV"] = prot["asc_putPositionV"] = prot.asc_putPositionV;
	prot["get_SizeRelH"] = prot["asc_getSizeRelH"] = prot.asc_getSizeRelH;
	prot["put_SizeRelH"] = prot["asc_putSizeRelH"] = prot.asc_putSizeRelH;
	prot["get_SizeRelV"] = prot["asc_getSizeRelV"] = prot.asc_getSizeRelV;
	prot["put_SizeRelV"] = prot["asc_putSizeRelV"] = prot.asc_putSizeRelV;
	prot["get_Value_X"] = prot["asc_getValue_X"] = prot.asc_getValue_X;
	prot["get_Value_Y"] = prot["asc_getValue_Y"] = prot.asc_getValue_Y;
	prot["get_ImageUrl"] = prot["asc_getImageUrl"] = prot.asc_getImageUrl;
	prot["put_ImageUrl"] = prot["asc_putImageUrl"] = prot.asc_putImageUrl;
	prot["get_Group"] = prot["asc_getGroup"] = prot.asc_getGroup;
	prot["put_Group"] = prot["asc_putGroup"] = prot.asc_putGroup;
	prot["get_FromGroup"] = prot["asc_getFromGroup"] = prot.asc_getFromGroup;
	prot["put_FromGroup"] = prot["asc_putFromGroup"] = prot.asc_putFromGroup;
	prot["get_isChartProps"] = prot["asc_getisChartProps"] = prot.asc_getisChartProps;
	prot["put_isChartPross"] = prot["asc_putisChartPross"] = prot.asc_putisChartPross;
	prot["get_SeveralCharts"] = prot["asc_getSeveralCharts"] = prot.asc_getSeveralCharts;
	prot["put_SeveralCharts"] = prot["asc_putSeveralCharts"] = prot.asc_putSeveralCharts;
	prot["get_SeveralChartTypes"] = prot["asc_getSeveralChartTypes"] = prot.asc_getSeveralChartTypes;
	prot["put_SeveralChartTypes"] = prot["asc_putSeveralChartTypes"] = prot.asc_putSeveralChartTypes;
	prot["get_SeveralChartStyles"] = prot["asc_getSeveralChartStyles"] = prot.asc_getSeveralChartStyles;
	prot["put_SeveralChartStyles"] = prot["asc_putSeveralChartStyles"] = prot.asc_putSeveralChartStyles;
	prot["get_VerticalTextAlign"] = prot["asc_getVerticalTextAlign"] = prot.asc_getVerticalTextAlign;
	prot["put_VerticalTextAlign"] = prot["asc_putVerticalTextAlign"] = prot.asc_putVerticalTextAlign;
	prot["get_Vert"] = prot["asc_getVert"] = prot.asc_getVert;
	prot["put_Vert"] = prot["asc_putVert"] = prot.asc_putVert;
	prot["get_Locked"] = prot["asc_getLocked"] = prot.asc_getLocked;
	prot["getLockAspect"] = prot["asc_getLockAspect"] = prot.asc_getLockAspect;
	prot["putLockAspect"] = prot["asc_putLockAspect"] = prot.asc_putLockAspect;
	prot["get_ChartProperties"] = prot["asc_getChartProperties"] = prot.asc_getChartProperties;
	prot["put_ChartProperties"] = prot["asc_putChartProperties"] = prot.asc_putChartProperties;
	prot["get_ShapeProperties"] = prot["asc_getShapeProperties"] = prot.asc_getShapeProperties;
	prot["put_ShapeProperties"] = prot["asc_putShapeProperties"] = prot.asc_putShapeProperties;
	prot["get_OriginSize"] = prot["asc_getOriginSize"] = prot.asc_getOriginSize;
	prot["get_PluginGuid"] = prot["asc_getPluginGuid"] = prot.asc_getPluginGuid;
	prot["put_PluginGuid"] = prot["asc_putPluginGuid"] = prot.asc_putPluginGuid;
	prot["get_PluginData"] = prot["asc_getPluginData"] = prot.asc_getPluginData;
	prot["put_PluginData"] = prot["asc_putPluginData"] = prot.asc_putPluginData;

	prot["get_Title"] = prot["asc_getTitle"] = prot.asc_getTitle;
	prot["put_Title"] = prot["asc_putTitle"] = prot.asc_putTitle;
	prot["get_Description"] = prot["asc_getDescription"] = prot.asc_getDescription;
	prot["put_Description"] = prot["asc_putDescription"] = prot.asc_putDescription;
	prot["get_ColumnNumber"] = prot["asc_getColumnNumber"] = prot.asc_getColumnNumber;
	prot["put_ColumnNumber"] = prot["asc_putColumnNumber"] = prot.asc_putColumnNumber;
	prot["get_ColumnSpace"] = prot["asc_getColumnSpace"] = prot.asc_getColumnSpace;
	prot["put_ColumnSpace"] = prot["asc_putColumnSpace"] = prot.asc_putColumnSpace;
	prot["asc_getSignatureId"] = prot["asc_getSignatureId"] = prot.asc_getSignatureId;




	window["AscCommon"].asc_CSelectedObject = asc_CSelectedObject;
	prot = asc_CSelectedObject.prototype;
	prot["get_ObjectType"] = prot["asc_getObjectType"] = prot.asc_getObjectType;
	prot["get_ObjectValue"] = prot["asc_getObjectValue"] = prot.asc_getObjectValue;

	window["Asc"]["asc_CShapeFill"] = window["Asc"].asc_CShapeFill = asc_CShapeFill;
	prot = asc_CShapeFill.prototype;
	prot["get_type"] = prot["asc_getType"] = prot.asc_getType;
	prot["put_type"] = prot["asc_putType"] = prot.asc_putType;
	prot["get_fill"] = prot["asc_getFill"] = prot.asc_getFill;
	prot["put_fill"] = prot["asc_putFill"] = prot.asc_putFill;
	prot["get_transparent"] = prot["asc_getTransparent"] = prot.asc_getTransparent;
	prot["put_transparent"] = prot["asc_putTransparent"] = prot.asc_putTransparent;
	prot["asc_CheckForseSet"] = prot["asc_CheckForseSet"] = prot.asc_CheckForseSet;

	window["Asc"]["asc_CFillBlip"] = window["Asc"].asc_CFillBlip = asc_CFillBlip;
	prot = asc_CFillBlip.prototype;
	prot["get_type"] = prot["asc_getType"] = prot.asc_getType;
	prot["put_type"] = prot["asc_putType"] = prot.asc_putType;
	prot["get_url"] = prot["asc_getUrl"] = prot.asc_getUrl;
	prot["put_url"] = prot["asc_putUrl"] = prot.asc_putUrl;
	prot["get_texture_id"] = prot["asc_getTextureId"] = prot.asc_getTextureId;
	prot["put_texture_id"] = prot["asc_putTextureId"] = prot.asc_putTextureId;

	window["Asc"]["asc_CFillHatch"] = window["Asc"].asc_CFillHatch = asc_CFillHatch;
	prot = asc_CFillHatch.prototype;
	prot["get_pattern_type"] = prot["asc_getPatternType"] = prot.asc_getPatternType;
	prot["put_pattern_type"] = prot["asc_putPatternType"] = prot.asc_putPatternType;
	prot["get_color_fg"] = prot["asc_getColorFg"] = prot.asc_getColorFg;
	prot["put_color_fg"] = prot["asc_putColorFg"] = prot.asc_putColorFg;
	prot["get_color_bg"] = prot["asc_getColorBg"] = prot.asc_getColorBg;
	prot["put_color_bg"] = prot["asc_putColorBg"] = prot.asc_putColorBg;

	window["Asc"]["asc_CFillGrad"] = window["Asc"].asc_CFillGrad = asc_CFillGrad;
	prot = asc_CFillGrad.prototype;
	prot["get_colors"] = prot["asc_getColors"] = prot.asc_getColors;
	prot["put_colors"] = prot["asc_putColors"] = prot.asc_putColors;
	prot["get_positions"] = prot["asc_getPositions"] = prot.asc_getPositions;
	prot["put_positions"] = prot["asc_putPositions"] = prot.asc_putPositions;
	prot["get_grad_type"] = prot["asc_getGradType"] = prot.asc_getGradType;
	prot["put_grad_type"] = prot["asc_putGradType"] = prot.asc_putGradType;
	prot["get_linear_angle"] = prot["asc_getLinearAngle"] = prot.asc_getLinearAngle;
	prot["put_linear_angle"] = prot["asc_putLinearAngle"] = prot.asc_putLinearAngle;
	prot["get_linear_scale"] = prot["asc_getLinearScale"] = prot.asc_getLinearScale;
	prot["put_linear_scale"] = prot["asc_putLinearScale"] = prot.asc_putLinearScale;
	prot["get_path_type"] = prot["asc_getPathType"] = prot.asc_getPathType;
	prot["put_path_type"] = prot["asc_putPathType"] = prot.asc_putPathType;

	window["Asc"]["asc_CFillSolid"] = window["Asc"].asc_CFillSolid = asc_CFillSolid;
	prot = asc_CFillSolid.prototype;
	prot["get_color"] = prot["asc_getColor"] = prot.asc_getColor;
	prot["put_color"] = prot["asc_putColor"] = prot.asc_putColor;

	window["Asc"]["asc_CStroke"] = window["Asc"].asc_CStroke = asc_CStroke;
	prot = asc_CStroke.prototype;
	prot["get_type"] = prot["asc_getType"] = prot.asc_getType;
	prot["put_type"] = prot["asc_putType"] = prot.asc_putType;
	prot["get_width"] = prot["asc_getWidth"] = prot.asc_getWidth;
	prot["put_width"] = prot["asc_putWidth"] = prot.asc_putWidth;
	prot["get_color"] = prot["asc_getColor"] = prot.asc_getColor;
	prot["put_color"] = prot["asc_putColor"] = prot.asc_putColor;
	prot["get_linejoin"] = prot["asc_getLinejoin"] = prot.asc_getLinejoin;
	prot["put_linejoin"] = prot["asc_putLinejoin"] = prot.asc_putLinejoin;
	prot["get_linecap"] = prot["asc_getLinecap"] = prot.asc_getLinecap;
	prot["put_linecap"] = prot["asc_putLinecap"] = prot.asc_putLinecap;
	prot["get_linebeginstyle"] = prot["asc_getLinebeginstyle"] = prot.asc_getLinebeginstyle;
	prot["put_linebeginstyle"] = prot["asc_putLinebeginstyle"] = prot.asc_putLinebeginstyle;
	prot["get_linebeginsize"] = prot["asc_getLinebeginsize"] = prot.asc_getLinebeginsize;
	prot["put_linebeginsize"] = prot["asc_putLinebeginsize"] = prot.asc_putLinebeginsize;
	prot["get_lineendstyle"] = prot["asc_getLineendstyle"] = prot.asc_getLineendstyle;
	prot["put_lineendstyle"] = prot["asc_putLineendstyle"] = prot.asc_putLineendstyle;
	prot["get_lineendsize"] = prot["asc_getLineendsize"] = prot.asc_getLineendsize;
	prot["put_lineendsize"] = prot["asc_putLineendsize"] = prot.asc_putLineendsize;
	prot["get_canChangeArrows"] = prot["asc_getCanChangeArrows"] = prot.asc_getCanChangeArrows;
	prot["put_prstDash"] = prot["asc_putPrstDash"] = prot.asc_putPrstDash;
	prot["get_prstDash"] = prot["asc_getPrstDash"] = prot.asc_getPrstDash;

	window["AscCommon"].CAscColorScheme = CAscColorScheme;
	prot = CAscColorScheme.prototype;
	prot["get_colors"] = prot.get_colors;
	prot["get_name"] = prot.get_name;

	window["AscCommon"].CMouseMoveData = CMouseMoveData;
	prot = CMouseMoveData.prototype;
	prot["get_Type"] = prot.get_Type;
	prot["get_X"] = prot.get_X;
	prot["get_Y"] = prot.get_Y;
	prot["get_Hyperlink"] = prot.get_Hyperlink;
	prot["get_UserId"] = prot.get_UserId;
	prot["get_HaveChanges"] = prot.get_HaveChanges;
	prot["get_LockedObjectType"] = prot.get_LockedObjectType;
	prot["get_FootnoteText"] =  prot.get_FootnoteText;
	prot["get_FootnoteNumber"] = prot.get_FootnoteNumber;

	window["Asc"]["asc_CUserInfo"] = window["Asc"].asc_CUserInfo = asc_CUserInfo;
	prot = asc_CUserInfo.prototype;
	prot["asc_putId"] = prot["put_Id"] = prot.asc_putId;
	prot["asc_getId"] = prot["get_Id"] = prot.asc_getId;
	prot["asc_putFullName"] = prot["put_FullName"] = prot.asc_putFullName;
	prot["asc_getFullName"] = prot["get_FullName"] = prot.asc_getFullName;
	prot["asc_putFirstName"] = prot["put_FirstName"] = prot.asc_putFirstName;
	prot["asc_getFirstName"] = prot["get_FirstName"] = prot.asc_getFirstName;
	prot["asc_putLastName"] = prot["put_LastName"] = prot.asc_putLastName;
	prot["asc_getLastName"] = prot["get_LastName"] = prot.asc_getLastName;

	window["Asc"]["asc_CDocInfo"] = window["Asc"].asc_CDocInfo = asc_CDocInfo;
	prot = asc_CDocInfo.prototype;
	prot["get_Id"] = prot["asc_getId"] = prot.asc_getId;
	prot["put_Id"] = prot["asc_putId"] = prot.asc_putId;
	prot["get_Url"] = prot["asc_getUrl"] = prot.asc_getUrl;
	prot["put_Url"] = prot["asc_putUrl"] = prot.asc_putUrl;
	prot["get_Title"] = prot["asc_getTitle"] = prot.asc_getTitle;
	prot["put_Title"] = prot["asc_putTitle"] = prot.asc_putTitle;
	prot["get_Format"] = prot["asc_getFormat"] = prot.asc_getFormat;
	prot["put_Format"] = prot["asc_putFormat"] = prot.asc_putFormat;
	prot["get_VKey"] = prot["asc_getVKey"] = prot.asc_getVKey;
	prot["put_VKey"] = prot["asc_putVKey"] = prot.asc_putVKey;
	prot["get_UserId"] = prot["asc_getUserId"] = prot.asc_getUserId;
	prot["get_UserName"] = prot["asc_getUserName"] = prot.asc_getUserName;
	prot["get_Options"] = prot["asc_getOptions"] = prot.asc_getOptions;
	prot["put_Options"] = prot["asc_putOptions"] = prot.asc_putOptions;
	prot["get_CallbackUrl"] = prot["asc_getCallbackUrl"] = prot.asc_getCallbackUrl;
	prot["put_CallbackUrl"] = prot["asc_putCallbackUrl"] = prot.asc_putCallbackUrl;
	prot["get_TemplateReplacement"] = prot["asc_getTemplateReplacement"] = prot.asc_getTemplateReplacement;
	prot["put_TemplateReplacement"] = prot["asc_putTemplateReplacement"] = prot.asc_putTemplateReplacement;
	prot["get_UserInfo"] = prot["asc_getUserInfo"] = prot.asc_getUserInfo;
	prot["put_UserInfo"] = prot["asc_putUserInfo"] = prot.asc_putUserInfo;
	prot["get_Token"] = prot["asc_getToken"] = prot.asc_getToken;
	prot["put_Token"] = prot["asc_putToken"] = prot.asc_putToken;
	prot["get_Mode"] = prot["asc_getMode"] = prot.asc_getMode;
	prot["put_Mode"] = prot["asc_putMode"] = prot.asc_putMode;
	prot["get_Permissions"] = prot["asc_getPermissions"] = prot.asc_getPermissions;
	prot["put_Permissions"] = prot["asc_putPermissions"] = prot.asc_putPermissions;
	prot["get_Lang"] = prot["asc_getLang"] = prot.asc_getLang;
	prot["put_Lang"] = prot["asc_putLang"] = prot.asc_putLang;
	prot["get_Encrypted"] = prot["asc_getEncrypted"] = prot.asc_getEncrypted;
	prot["put_Encrypted"] = prot["asc_putEncrypted"] = prot.asc_putEncrypted;

	window["AscCommon"].COpenProgress = COpenProgress;
	prot = COpenProgress.prototype;
	prot["asc_getType"] = prot.asc_getType;
	prot["asc_getFontsCount"] = prot.asc_getFontsCount;
	prot["asc_getCurrentFont"] = prot.asc_getCurrentFont;
	prot["asc_getImagesCount"] = prot.asc_getImagesCount;
	prot["asc_getCurrentImage"] = prot.asc_getCurrentImage;

	window["AscCommon"].CErrorData = CErrorData;
	prot = CErrorData.prototype;
	prot["put_Value"] = prot.put_Value;
	prot["get_Value"] = prot.get_Value;

	window["AscCommon"].CAscMathType = CAscMathType;
	prot = CAscMathType.prototype;
	prot["get_Id"] = prot.get_Id;
	prot["get_X"] = prot.get_X;
	prot["get_Y"] = prot.get_Y;

	window["AscCommon"].CAscMathCategory = CAscMathCategory;
	prot = CAscMathCategory.prototype;
	prot["get_Id"] = prot.get_Id;
	prot["get_Data"] = prot.get_Data;
	prot["get_W"] = prot.get_W;
	prot["get_H"] = prot.get_H;

	window["AscCommon"].CStyleImage = CStyleImage;
	prot = CStyleImage.prototype;
	prot["asc_getName"] = prot["get_Name"] = prot.asc_getName;
	prot["asc_getType"] = prot["get_Type"] = prot.asc_getType;
	prot["asc_getImage"] = prot.asc_getImage;

    window["AscCommon"].asc_CSpellCheckProperty = asc_CSpellCheckProperty;
    prot = asc_CSpellCheckProperty.prototype;
    prot["get_Word"] = prot.get_Word;
    prot["get_Checked"] = prot.get_Checked;
    prot["get_Variants"] = prot.get_Variants;

    window["AscCommon"].CWatermarkOnDraw = CWatermarkOnDraw;

	window["Asc"]["CPluginVariation"] = window["Asc"].CPluginVariation = CPluginVariation;
	window["Asc"]["CPlugin"] = window["Asc"].CPlugin = CPlugin;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(function(window, undefined){

//зависимости
//stream
//memory
//c_oAscChartType
//todo
//BinaryCommonWriter

	function inherit(proto) {
		function F() {}
		F.prototype = proto;
		return new F;
	}
	if (!Object.create || !Object['create']) Object['create'] = Object.create = inherit;

var c_oSerConstants = {
    ErrorFormat: -2,
    ErrorUnknown: -1,
    ReadOk:0,
    ReadUnknown:1,
    ErrorStream:0x55
};
var c_oSerPropLenType = {
    Null:0,
    Byte:1,
    Short:2,
    Three:3,
    Long:4,
    Double:5,
    Variable:6
};
var c_oSer_ColorObjectType =
{
    Rgb: 0,
    Type: 1,
    Theme: 2,
    Tint: 3
};
var c_oSer_ColorType =
{
    Auto: 0
};
var c_oSerBorderType = {
    Color: 0,
    Space: 1,
    Size: 2,
    Value: 3,
	ColorTheme: 4
};
var c_oSerBordersType = {
    left: 0,
    top: 1,
    right: 2,
    bottom: 3,
    insideV: 4,
    insideH: 5,
    start: 6,
    end: 7,
    tl2br: 8,
    tr2bl: 9,
    bar: 10,
    between: 11
};
var c_oSerPaddingType = {
    left: 0,
    top: 1,
    right: 2,
    bottom: 3
};
var c_oSerShdType = {
    Value: 0,
    Color: 1,
	ColorTheme: 2
};
  var c_oSer_ColorThemeType = {
    Auto: 0,
    Color: 1,
    Tint: 2,
    Shade: 3
  };
	var c_oSerBookmark = {
		Id: 0,
		Name: 1,
		DisplacedByCustomXml: 2,
		ColFirst: 3,
		ColLast: 4
	};

function BinaryCommonWriter(memory)
{
    this.memory = memory;
}
BinaryCommonWriter.prototype.WriteItem = function(type, fWrite)
{
    //type
    this.memory.WriteByte(type);
    this.WriteItemWithLength(fWrite);
};
BinaryCommonWriter.prototype.WriteItemStart = function(type, fWrite)
{
	this.memory.WriteByte(type);
    return this.WriteItemWithLengthStart(fWrite);
};
BinaryCommonWriter.prototype.WriteItemEnd = function(nStart)
{
	this.WriteItemWithLengthEnd(nStart);
};
BinaryCommonWriter.prototype.WriteItemWithLength = function(fWrite)
{
    var nStart = this.WriteItemWithLengthStart();
    fWrite();
    this.WriteItemWithLengthEnd(nStart);
};
BinaryCommonWriter.prototype.WriteItemWithLengthStart = function()
{
    //Запоминаем позицию чтобы в конце записать туда длину
    var nStart = this.memory.GetCurPosition();
    this.memory.Skip(4);
    return nStart;
};
BinaryCommonWriter.prototype.WriteItemWithLengthEnd = function(nStart)
{
    //Length
    var nEnd = this.memory.GetCurPosition();
    this.memory.Seek(nStart);
    this.memory.WriteLong(nEnd - nStart - 4);
    this.memory.Seek(nEnd);
};
BinaryCommonWriter.prototype.WriteBorder = function(border)
{
	var _this = this;
    if(null != border.Value)
    {
        var color = null;
        if (null != border.Color)
            color = border.Color;
        else if (null != border.Unifill) {
            var doc = window.editor.WordControl.m_oLogicDocument;
            border.Unifill.check(doc.Get_Theme(), doc.Get_ColorMap());
            var RGBA = border.Unifill.getRGBAColor();
            color = new window['AscCommonWord'].CDocumentColor(RGBA.R, RGBA.G, RGBA.B);
        }
        if (null != color && !color.Auto)
            this.WriteColor(c_oSerBorderType.Color, color);
        if (null != border.Space) {
            this.memory.WriteByte(c_oSerBorderType.Space);
            this.memory.WriteByte(c_oSerPropLenType.Double);
            this.memory.WriteDouble(border.Space);
        }
        if (null != border.Size) {
            this.memory.WriteByte(c_oSerBorderType.Size);
            this.memory.WriteByte(c_oSerPropLenType.Double);
            this.memory.WriteDouble(border.Size);
        }
        if (null != border.Unifill || (null != border.Color && border.Color.Auto)) {
            this.memory.WriteByte(c_oSerBorderType.ColorTheme);
            this.memory.WriteByte(c_oSerPropLenType.Variable);
            this.WriteItemWithLength(function () { _this.WriteColorTheme(border.Unifill, border.Color); });
        }

        this.memory.WriteByte(c_oSerBorderType.Value);
        this.memory.WriteByte(c_oSerPropLenType.Byte);
        this.memory.WriteByte(border.Value);
    }
};
BinaryCommonWriter.prototype.WriteBorders = function(Borders)
{
    var oThis = this;
    //Left
    if(null != Borders.Left)
        this.WriteItem(c_oSerBordersType.left, function(){oThis.WriteBorder(Borders.Left);});
    //Top
    if(null != Borders.Top)
        this.WriteItem(c_oSerBordersType.top, function(){oThis.WriteBorder(Borders.Top);});
    //Right
    if(null != Borders.Right)
        this.WriteItem(c_oSerBordersType.right, function(){oThis.WriteBorder(Borders.Right);});
    //Bottom
    if(null != Borders.Bottom)
        this.WriteItem(c_oSerBordersType.bottom, function(){oThis.WriteBorder(Borders.Bottom);});
    //InsideV
    if(null != Borders.InsideV)
        this.WriteItem(c_oSerBordersType.insideV, function(){oThis.WriteBorder(Borders.InsideV);});
    //InsideH
    if(null != Borders.InsideH)
        this.WriteItem(c_oSerBordersType.insideH, function(){oThis.WriteBorder(Borders.InsideH);});
    //Between
    if(null != Borders.Between)
        this.WriteItem(c_oSerBordersType.between, function(){oThis.WriteBorder(Borders.Between);});
};
BinaryCommonWriter.prototype.WriteColor = function(type, color)
{
    this.memory.WriteByte(type);
    this.memory.WriteByte(c_oSerPropLenType.Three);
    this.memory.WriteByte(color.r);
    this.memory.WriteByte(color.g);
    this.memory.WriteByte(color.b);
};
BinaryCommonWriter.prototype.WriteShd = function(Shd)
{
	var _this = this;
    //Value
    if(null != Shd.Value)
    {
        this.memory.WriteByte(c_oSerShdType.Value);
        this.memory.WriteByte(c_oSerPropLenType.Byte);
        this.memory.WriteByte(Shd.Value);
    }
    //Value
    var color = null;
    if (null != Shd.Color)
        color = Shd.Color;
    else if (null != Shd.Unifill) {
        var doc = editor.WordControl.m_oLogicDocument;
        Shd.Unifill.check(doc.Get_Theme(), doc.Get_ColorMap());
        var RGBA = Shd.Unifill.getRGBAColor();
        color = new AscCommonWord.CDocumentColor(RGBA.R, RGBA.G, RGBA.B);
    }
    if (null != color && !color.Auto)
        this.WriteColor(c_oSerShdType.Color, color);
	if(null != Shd.Unifill || (null != Shd.Color && Shd.Color.Auto))
    {
		this.memory.WriteByte(c_oSerShdType.ColorTheme);
		this.memory.WriteByte(c_oSerPropLenType.Variable);
		this.WriteItemWithLength(function(){_this.WriteColorTheme(Shd.Unifill, Shd.Color);});
    }
};
BinaryCommonWriter.prototype.WritePaddings = function(Paddings)
{
    //left
    if(null != Paddings.L)
    {
        this.memory.WriteByte(c_oSerPaddingType.left);
        this.memory.WriteByte(c_oSerPropLenType.Double);
        this.memory.WriteDouble(Paddings.L);
    }
    //top
    if(null != Paddings.T)
    {
        this.memory.WriteByte(c_oSerPaddingType.top);
        this.memory.WriteByte(c_oSerPropLenType.Double);
        this.memory.WriteDouble(Paddings.T);
    }
    //Right
    if(null != Paddings.R)
    {
        this.memory.WriteByte(c_oSerPaddingType.right);
        this.memory.WriteByte(c_oSerPropLenType.Double);
        this.memory.WriteDouble(Paddings.R);
    }
    //bottom
    if(null != Paddings.B)
    {
        this.memory.WriteByte(c_oSerPaddingType.bottom);
        this.memory.WriteByte(c_oSerPropLenType.Double);
        this.memory.WriteDouble(Paddings.B);
    }
};
BinaryCommonWriter.prototype.WriteColorSpreadsheet = function(color)
{
	if(color instanceof AscCommonExcel.ThemeColor)
	{
		if(null != color.theme)
		{
			this.memory.WriteByte(c_oSer_ColorObjectType.Theme);
			this.memory.WriteByte(c_oSerPropLenType.Byte);
			this.memory.WriteByte(color.theme);
		}
		if(null != color.tint)
		{
			this.memory.WriteByte(c_oSer_ColorObjectType.Tint);
			this.memory.WriteByte(c_oSerPropLenType.Double);
			this.memory.WriteDouble2(color.tint);
		}
	}
	else
	{
		this.memory.WriteByte(c_oSer_ColorObjectType.Rgb);
		this.memory.WriteByte(c_oSerPropLenType.Long);
		this.memory.WriteLong(color.getRgb());
	}
};
BinaryCommonWriter.prototype.WriteColorTheme = function(unifill, color)
{
	if(null != color && color.Auto){
		this.memory.WriteByte(c_oSer_ColorThemeType.Auto);
		this.memory.WriteByte(c_oSerPropLenType.Null);
	}
	if (null != unifill && null != unifill.fill && null != unifill.fill.color && unifill.fill.color.color instanceof AscFormat.CSchemeColor) {
		var uniColor = unifill.fill.color;
		if(null != uniColor.color){
      var EThemeColor = AscCommonWord.EThemeColor;
			var nFormatId = EThemeColor.themecolorNone;
			switch(uniColor.color.id){
				case 0: nFormatId = EThemeColor.themecolorAccent1;break;
				case 1: nFormatId = EThemeColor.themecolorAccent2;break;
				case 2: nFormatId = EThemeColor.themecolorAccent3;break;
				case 3: nFormatId = EThemeColor.themecolorAccent4;break;
				case 4: nFormatId = EThemeColor.themecolorAccent5;break;
				case 5: nFormatId = EThemeColor.themecolorAccent6;break;
				case 6: nFormatId = EThemeColor.themecolorBackground1;break;
				case 7: nFormatId = EThemeColor.themecolorBackground2;break;
				case 8: nFormatId = EThemeColor.themecolorDark1;break;
				case 9: nFormatId = EThemeColor.themecolorDark2;break;
				case 10: nFormatId = EThemeColor.themecolorFollowedHyperlink;break;
				case 11: nFormatId = EThemeColor.themecolorHyperlink;break;
				case 12: nFormatId = EThemeColor.themecolorLight1;break;
				case 13: nFormatId = EThemeColor.themecolorLight2;break;
				case 14: nFormatId = EThemeColor.themecolorNone;break;
				case 15: nFormatId = EThemeColor.themecolorText1;break;
				case 16: nFormatId = EThemeColor.themecolorText2;break;
			}
			this.memory.WriteByte(c_oSer_ColorThemeType.Color);
			this.memory.WriteByte(c_oSerPropLenType.Byte);
			this.memory.WriteByte(nFormatId);
		}
		if(null != uniColor.Mods){
			for(var i = 0, length = uniColor.Mods.Mods.length; i < length; ++i){
				var mod = uniColor.Mods.Mods[i];
				if("wordTint" == mod.name){
					this.memory.WriteByte(c_oSer_ColorThemeType.Tint);
					this.memory.WriteByte(c_oSerPropLenType.Byte);
					this.memory.WriteByte(Math.round(mod.val));
				}
				else if("wordShade" == mod.name){
					this.memory.WriteByte(c_oSer_ColorThemeType.Shade);
					this.memory.WriteByte(c_oSerPropLenType.Byte);
					this.memory.WriteByte(Math.round(mod.val));
				}
			}
		}
	}
};
BinaryCommonWriter.prototype.WriteBookmark = function(bookmark) {
	var oThis = this;
	if (null !== bookmark.BookmarkId) {
		this.WriteItem(c_oSerBookmark.Id, function() {
			oThis.memory.WriteLong(bookmark.BookmarkId);
		});
	}
	if (bookmark.IsStart() && null !== bookmark.BookmarkName) {
		this.memory.WriteByte(c_oSerBookmark.Name);
		this.memory.WriteString2(bookmark.BookmarkName);
	}
};
function Binary_CommonReader(stream)
{
    this.stream = stream;
}

Binary_CommonReader.prototype.ReadTable = function(fReadContent)
{
    var res = c_oSerConstants.ReadOk;
    //stLen
    res = this.stream.EnterFrame(4);
    if(c_oSerConstants.ReadOk != res)
        return res;
    var stLen = this.stream.GetULongLE();
    //Смотрим есть ли данные под всю таблицу в дальнейшем спокойно пользуемся get функциями
    res = this.stream.EnterFrame(stLen);
    if(c_oSerConstants.ReadOk != res)
        return res;
    return this.Read1(stLen, fReadContent);
};
Binary_CommonReader.prototype.Read1 = function(stLen, fRead)
{
    var res = c_oSerConstants.ReadOk;
    var stCurPos = 0;
    while(stCurPos < stLen)
    {
		this.stream.bLast = false;
        //stItem
        var type = this.stream.GetUChar();
        var length = this.stream.GetULongLE();
		if (stCurPos + length + 5 >= stLen)
			this.stream.bLast = true;
        res = fRead(type, length);
        if(res === c_oSerConstants.ReadUnknown)
        {
            res = this.stream.Skip2(length);
            if(c_oSerConstants.ReadOk != res)
                return res;
        }
        else if(res !== c_oSerConstants.ReadOk)
            return res;
        stCurPos += length + 5;
    }
    return res;
};
Binary_CommonReader.prototype.Read2 = function(stLen, fRead)
{
    var res = c_oSerConstants.ReadOk;
    var stCurPos = 0;
    while(stCurPos < stLen)
    {
        //stItem
        var type = this.stream.GetUChar();
        var lenType = this.stream.GetUChar();
        var nCurPosShift = 2;
        var nRealLen;
        switch(lenType)
        {
            case c_oSerPropLenType.Null: nRealLen = 0;break;
            case c_oSerPropLenType.Byte: nRealLen = 1;break;
            case c_oSerPropLenType.Short: nRealLen = 2;break;
            case c_oSerPropLenType.Three: nRealLen = 3;break;
            case c_oSerPropLenType.Long:
            case c_oSerPropLenType.Double: nRealLen = 4;break;
            case c_oSerPropLenType.Variable:
                nRealLen = this.stream.GetULongLE();
                nCurPosShift += 4;
                break;
            default:return c_oSerConstants.ErrorUnknown;
        }
        res = fRead(type, nRealLen);
        if(res === c_oSerConstants.ReadUnknown)
        {
            res = this.stream.Skip2(nRealLen);
            if(c_oSerConstants.ReadOk != res)
                return res;
        }
        else if(res !== c_oSerConstants.ReadOk)
            return res;
        stCurPos += nRealLen + nCurPosShift;
    }
    return res;
};
Binary_CommonReader.prototype.Read2Spreadsheet = function(stLen, fRead)
{
    var res = c_oSerConstants.ReadOk;
    var stCurPos = 0;
    while(stCurPos < stLen)
    {
        //stItem
        var type = this.stream.GetUChar();
        var lenType = this.stream.GetUChar();
        var nCurPosShift = 2;
        var nRealLen;
        switch(lenType)
        {
            case c_oSerPropLenType.Null: nRealLen = 0;break;
            case c_oSerPropLenType.Byte: nRealLen = 1;break;
            case c_oSerPropLenType.Short: nRealLen = 2;break;
            case c_oSerPropLenType.Three: nRealLen = 3;break;
            case c_oSerPropLenType.Long: nRealLen = 4;break;
            case c_oSerPropLenType.Double: nRealLen = 8;break;
            case c_oSerPropLenType.Variable:
                nRealLen = this.stream.GetULongLE();
                nCurPosShift += 4;
                break;
            default:return c_oSerConstants.ErrorUnknown;
        }
        res = fRead(type, nRealLen);
        if(res === c_oSerConstants.ReadUnknown)
        {
            res = this.stream.Skip2(nRealLen);
            if(c_oSerConstants.ReadOk != res)
                return res;
        }
        else if(res !== c_oSerConstants.ReadOk)
            return res;
        stCurPos += nRealLen + nCurPosShift;
    }
    return res;
};
Binary_CommonReader.prototype.ReadDouble = function()
{
    var dRes = 0.0;
    dRes |= this.stream.GetUChar();
    dRes |= this.stream.GetUChar() << 8;
    dRes |= this.stream.GetUChar() << 16;
    dRes |= this.stream.GetUChar() << 24;
    dRes /= 100000;
    return dRes;
};
Binary_CommonReader.prototype.ReadColor = function()
{
    var r = this.stream.GetUChar();
    var g = this.stream.GetUChar();
    var b = this.stream.GetUChar();
    return new AscCommonWord.CDocumentColor(r, g, b);
};
Binary_CommonReader.prototype.ReadShd = function(type, length, Shd, themeColor)
{
    var res = c_oSerConstants.ReadOk;
	var oThis = this;
    switch(type)
    {
        case c_oSerShdType.Value: Shd.Value = this.stream.GetUChar();break;
        case c_oSerShdType.Color: Shd.Color = this.ReadColor();break;
		case c_oSerShdType.ColorTheme:
			res = this.Read2(length, function(t, l){
				return oThis.ReadColorTheme(t, l, themeColor);
			});
			break;
        default:
            res = c_oSerConstants.ReadUnknown;
            break;
    }
    return res;
};
Binary_CommonReader.prototype.ReadColorSpreadsheet = function(type, length, color)
{
    var res = c_oSerConstants.ReadOk;
    if ( c_oSer_ColorObjectType.Type == type )
        color.auto = (c_oSer_ColorType.Auto == this.stream.GetUChar());
    else if ( c_oSer_ColorObjectType.Rgb == type )
        color.rgb = 0xffffff & this.stream.GetULongLE();
	else if ( c_oSer_ColorObjectType.Theme == type )
        color.theme = this.stream.GetUChar();
	else if ( c_oSer_ColorObjectType.Tint == type )
        color.tint = this.stream.GetDoubleLE();
    else
        res = c_oSerConstants.ReadUnknown;
    return res;
};
Binary_CommonReader.prototype.ReadColorTheme = function(type, length, color)
{
    var res = c_oSerConstants.ReadOk;
    if ( c_oSer_ColorThemeType.Auto == type )
        color.Auto = true;
	else if ( c_oSer_ColorThemeType.Color == type )
        color.Color = this.stream.GetByte();
	else if ( c_oSer_ColorThemeType.Tint == type )
        color.Tint = this.stream.GetByte();
	else if ( c_oSer_ColorThemeType.Shade == type )
        color.Shade = this.stream.GetByte();
    else
        res = c_oSerConstants.ReadUnknown;
    return res;
};
Binary_CommonReader.prototype.ReadBookmark = function(type, length, bookmark) {
	var res = c_oSerConstants.ReadOk;
	if (c_oSerBookmark.Id === type) {
		bookmark.BookmarkId = this.stream.GetULongLE();
	} else if (c_oSerBookmark.Name === type) {
		bookmark.BookmarkName = this.stream.GetString2LE(length);
	} else {
		res = c_oSerConstants.ReadUnknown;
	}
	return res;
};
/** @constructor */
function FT_Stream2(data, size) {
    this.obj = null;
    this.data = data;
    this.size = size;
    this.pos = 0;
    this.cur = 0;
	this.bLast = false;
}

FT_Stream2.prototype.Seek = function(_pos) {
	if (_pos > this.size)
		return c_oSerConstants.ErrorStream;
	this.pos = _pos;
	return c_oSerConstants.ReadOk;
};
FT_Stream2.prototype.Seek2 = function(_cur) {
	if (_cur > this.size)
		return c_oSerConstants.ErrorStream;
	this.cur = _cur;
	return c_oSerConstants.ReadOk;
};
FT_Stream2.prototype.Skip = function(_skip) {
	if (_skip < 0)
		return c_oSerConstants.ErrorStream;
	return this.Seek(this.pos + _skip);
};
FT_Stream2.prototype.Skip2 = function(_skip) {
	if (_skip < 0)
		return c_oSerConstants.ErrorStream;
	return this.Seek2(this.cur + _skip);
};

// 1 bytes
FT_Stream2.prototype.GetUChar = function() {
	if (this.cur >= this.size)
		return 0;
	return this.data[this.cur++];
};
FT_Stream2.prototype.GetChar = function() {
	if (this.cur >= this.size)
        return 0;
    var m = this.data[this.cur++];
    if (m > 127)
        m -= 256;
    return m;
};
FT_Stream2.prototype.GetByte = function() {
	return this.GetUChar();
};
FT_Stream2.prototype.GetBool = function() {
	var Value = this.GetUChar();
	return ( Value == 0 ? false : true );
};
// 2 byte
FT_Stream2.prototype.GetUShortLE = function() {
	if (this.cur + 1 >= this.size)
		return 0;
	return (this.data[this.cur++] | this.data[this.cur++] << 8);
};
// 4 byte
FT_Stream2.prototype.GetULongLE = function() {
	if (this.cur + 3 >= this.size)
		return 0;
	return (this.data[this.cur++] | this.data[this.cur++] << 8 | this.data[this.cur++] << 16 | this.data[this.cur++] << 24);
};
FT_Stream2.prototype.GetLongLE = function() {
	return this.GetULongLE();
};
FT_Stream2.prototype.GetLong = function() {
	return this.GetULongLE();
};
	var tempHelp = new ArrayBuffer(8);
	var tempHelpUnit = new Uint8Array(tempHelp);
	var tempHelpFloat = new Float64Array(tempHelp);
FT_Stream2.prototype.GetDoubleLE = function() {
	if (this.cur + 7 >= this.size)
		return 0;
	tempHelpUnit[0] = this.GetUChar();
	tempHelpUnit[1] = this.GetUChar();
	tempHelpUnit[2] = this.GetUChar();
	tempHelpUnit[3] = this.GetUChar();
	tempHelpUnit[4] = this.GetUChar();
	tempHelpUnit[5] = this.GetUChar();
	tempHelpUnit[6] = this.GetUChar();
	tempHelpUnit[7] = this.GetUChar();
	return tempHelpFloat[0];

	var arr = [];
	for(var i = 0; i < 8; ++i)
		arr.push(this.GetUChar());
	return this.doubleDecodeLE754(arr);
};
FT_Stream2.prototype.doubleDecodeLE754 = function(a) {
	var s, e, m, i, d, nBits, mLen, eLen, eBias, eMax;
	var el = {len:8, mLen:52, rt:0};
	mLen = el.mLen, eLen = el.len*8-el.mLen-1, eMax = (1<<eLen)-1, eBias = eMax>>1;

	i = (el.len-1); d = -1; s = a[i]; i+=d; nBits = -7;
	for (e = s&((1<<(-nBits))-1), s>>=(-nBits), nBits += eLen; nBits > 0; e=e*256+a[i], i+=d, nBits-=8);
	for (m = e&((1<<(-nBits))-1), e>>=(-nBits), nBits += mLen; nBits > 0; m=m*256+a[i], i+=d, nBits-=8);

	switch (e)
	{
		case 0:
			// Zero, or denormalized number
			e = 1-eBias;
			break;
		case eMax:
			// NaN, or +/-Infinity
			return m?NaN:((s?-1:1)*Infinity);
		default:
			// Normalized number
			m = m + Math.pow(2, mLen);
			e = e - eBias;
			break;
	}
	return (s?-1:1) * m * Math.pow(2, e-mLen);
};
// 3 byte
FT_Stream2.prototype.GetUOffsetLE = function() {
	if (this.cur + 2 >= this.size)
		return c_oSerConstants.ReadOk;
	return (this.data[this.cur++] | this.data[this.cur++] << 8 | this.data[this.cur++] << 16);
};
FT_Stream2.prototype.GetString2 = function() {
	var Len = this.GetLong();
	return this.GetString2LE(Len);
};
//String
FT_Stream2.prototype.GetString2LE = function(len) {
	if (this.cur + len > this.size)
		return "";
	var a = [];
	for (var i = 0; i + 1 < len; i+=2)
		a.push(String.fromCharCode(this.data[this.cur + i] | this.data[this.cur + i + 1] << 8));
	this.cur += len;
	return a.join("");
};
FT_Stream2.prototype.GetString = function() {
	var Len = this.GetLong();
	if (this.cur + 2 * Len > this.size)
		return "";
	var t = "";
	for (var i = 0; i + 1 < 2 * Len; i+=2) {
		var uni = this.data[this.cur + i];
		uni |= this.data[this.cur + i + 1] << 8;
		t += String.fromCharCode(uni);
	}
	this.cur += 2 * Len;
	return t;
};
FT_Stream2.prototype.GetCurPos = function() {
	return this.cur;
};
FT_Stream2.prototype.GetSize = function() {
	return this.size;
};
FT_Stream2.prototype.EnterFrame = function(count) {
	if (this.size - this.pos < count)
		return c_oSerConstants.ErrorStream;

	this.cur = this.pos;
	this.pos += count;
	return c_oSerConstants.ReadOk;
};
FT_Stream2.prototype.GetDouble = function() {
	var dRes = 0.0;
	dRes |= this.GetUChar();
	dRes |= this.GetUChar() << 8;
	dRes |= this.GetUChar() << 16;
	dRes |= this.GetUChar() << 24;
	dRes /= 100000;
	return dRes;
};
FT_Stream2.prototype.GetBuffer = function(length) {
	var res = new Array(length);
	for(var i = 0 ; i < length ;++i){
		res[i] = this.data[this.cur++]
	}
	return res;
};
var gc_nMaxRow = 1048576;
var gc_nMaxCol = 16384;
var gc_nMaxRow0 = gc_nMaxRow - 1;
var gc_nMaxCol0 = gc_nMaxCol - 1;
/**
 * @constructor
 */
function CellAddressUtils(){
	this._oCodeA = 'A'.charCodeAt(0);
	this._aColnumToColstr = [];
	this.oCellAddressCache = {};
	this.colnumToColstrFromWsView = function (col) {
		var sResult = this._aColnumToColstr[col];
		if (null != sResult)
			return sResult;

		if(col == 0) return "";

		var col0 = col - 1;
		var text = String.fromCharCode(65 + (col0 % 26));
		return (this._aColnumToColstr[col] = (col0 < 26 ? text : this.colnumToColstrFromWsView(Math.floor(col0 / 26)) + text));
	};
	this.colnumToColstr = function(num){
		var sResult = this._aColnumToColstr[num];
		if(!sResult){
			// convert 1 to A, 2 to B, ..., 27 to AA etc.
			sResult = "";
			if(num > 0){
				var columnNumber = num;
				var currentLetterNumber;
				while(columnNumber > 0){
					currentLetterNumber = (columnNumber - 1) % 26;
					sResult = String.fromCharCode(currentLetterNumber + 65) + sResult;
					columnNumber = (columnNumber - (currentLetterNumber + 1)) / 26;
				}
			}
			this._aColnumToColstr[num] = sResult;
		}
		return sResult;
	};
	this.colstrToColnum = function(col_str) {
		//convert A to 1; AA to 27
		var col_num = 0;
		for (var i = 0; i < col_str.length; ++i)
			col_num = 26 * col_num + (col_str.charCodeAt(i) - this._oCodeA + 1);
		return col_num;
	};
	this.getCellId = function(row, col){
		return g_oCellAddressUtils.colnumToColstr(col + 1) + (row + 1);
	};
	this.getCellAddress = function(sId)
	{
		var oRes = this.oCellAddressCache[sId];
		if(null == oRes)
		{
			oRes = new CellAddress(sId);
			this.oCellAddressCache[sId] = oRes;
		}
		return oRes;
	};
}
var g_oCellAddressUtils = new CellAddressUtils();

	function CellBase(r, c) {
		this.row = r;
		this.col = c;
	}
	CellBase.prototype.clean = function() {
		this.row = 0;
		this.col = 0;
	};
	CellBase.prototype.clone = function() {
		return new CellBase(this.row, this.col);
	};
	CellBase.prototype.isEqual = function(cell) {
		return this.row === cell.row && this.col === cell.col;
	};
	CellBase.prototype.isEmpty = function() {
		return 0 === this.row && 0 === this.col;
	};
	CellBase.prototype.getName = function() {
		return g_oCellAddressUtils.colnumToColstr(this.col + 1) + (this.row + 1);
	};
/**
 * @constructor
 */
function CellAddress(){
	var argc = arguments.length;
	this._valid = true;
	this._invalidId = false;
	this._invalidCoord = false;
	this.id = null;
	this.row = null;
	this.col = null;
	this.bRowAbs = false;
	this.bColAbs = false;
	this.bIsCol = false;
	this.bIsRow = false;
	this.colLetter = null;
	if(1 == argc){
		//Сразу пришло ID вида "A1"
		this.id = arguments[0].toUpperCase();
		this._invalidCoord = true;
		this._checkId();
	}
	else if(2 == argc){
		//адрес вида (1,1) = "A1". Внутренний формат начинается с 1
		this.row = arguments[0];
		this.col = arguments[1];
		this._checkCoord();
		this._invalidId = true;
	}
	else if(3 == argc){
		//тоже самое что и 2 аргумента, только 0-based
		this.row = arguments[0] + 1;
		this.col = arguments[1] + 1;
		this._checkCoord();
		this._invalidId = true;
	}
}
CellAddress.prototype = Object.create(CellBase.prototype);
CellAddress.prototype.constructor = CellAddress;
CellAddress.prototype._isDigit=function(symbol){
	return '0' <= symbol && symbol <= '9';
};
CellAddress.prototype._isAlpha=function(symbol){
	return 'A' <= symbol && symbol <= 'Z';
};
CellAddress.prototype._checkId=function(){
	this._invalidCoord = true;
	this._recalculate(true, false);
	this._checkCoord();
};
CellAddress.prototype._checkCoord=function(){
	if( !(this.row >= 1 && this.row <= gc_nMaxRow) )
		this._valid = false;
	else if( !(this.col >= 1 && this.col <= gc_nMaxCol) )
		this._valid = false;
	else
		this._valid = true;
};
CellAddress.prototype._recalculate=function(bCoord, bId){
	if(bCoord && this._invalidCoord){
		this._invalidCoord = false;
		var sId = this.id;
		this.row = this.col = 0;//выставляем невалидные значения, чтобы не присваивать их при каждом else
		var indexes = {}, i = -1, indexesCount = 0;
		while ((i = sId.indexOf("$", i + 1)) != -1) {
		    indexes[i - indexesCount++] = 1;//отнимаем количество, чтобы индексы указывали на следующий после них символ после удаления $
		}
		if (indexesCount <= 2) {
		    if (indexesCount > 0)
		        sId = sId.replace(/\$/g, "");
		    var nIdLength = sId.length;
		    if (nIdLength > 0) {
		        var nIndex = 0;
		        while (this._isAlpha(sId.charAt(nIndex)) && nIndex < nIdLength)
		            nIndex++;
		        if (0 == nIndex) {
		            //  (1,Infinity)
		            this.bIsRow = true;
		            this.col = 1;
		            this.colLetter = g_oCellAddressUtils.colnumToColstr(this.col);
		            this.row = sId.substring(nIndex) - 0;
		            //this.id = this.colLetter + this.row;
		            if (null != indexes[0]) {
		                this.bRowAbs = true;
		                indexesCount--;
		            }
		        }
		        else if (nIndex == nIdLength) {
		            //  (Infinity,1)
		            this.bIsCol = true;
		            this.colLetter = sId;
		            this.col = g_oCellAddressUtils.colstrToColnum(this.colLetter);
		            this.row = 1;
		            //this.id = this.colLetter + this.row;
		            if (null != indexes[0]) {
		                this.bColAbs = true;
		                indexesCount--;
		            }
		        }
		        else {
		            this.colLetter = sId.substring(0, nIndex);
		            this.col = g_oCellAddressUtils.colstrToColnum(this.colLetter);
		            this.row = sId.substring(nIndex) - 0;
		            if (null != indexes[0]) {
		                this.bColAbs = true;
		                indexesCount--;
		            }
		            if (null != indexes[nIndex]) {
		                this.bRowAbs = true;
		                indexesCount--;
		            }
		        }
		        if (indexesCount > 0) {
		            this.row = this.col = 0;
		        }
		    }
		}
	}
	else if(bId && this._invalidId){
		this._invalidId = false;
		this.colLetter = g_oCellAddressUtils.colnumToColstr(this.col);
		if(this.bIsCol)
			this.id = this.colLetter;
		else if(this.bIsRow)
			this.id = this.row;
		else
			this.id = this.colLetter + this.row;
	}
};
CellAddress.prototype.isValid=function(){
	return this._valid;
};
CellAddress.prototype.getID=function(){
	this._recalculate(false, true);
	return this.id;
};
CellAddress.prototype.getIDAbsolute=function(){
	this._recalculate(true, false);
	return "$" + this.getColLetter() + "$" + this.getRow();
};
CellAddress.prototype.getRow=function(){
	this._recalculate(true, false);
	return this.row;
};
CellAddress.prototype.getRow0=function(){
	//0 - based
	this._recalculate(true, false);
	return this.row - 1;
};
CellAddress.prototype.getRowAbs=function(){
	this._recalculate(true, false);
	return this.bRowAbs;
};
CellAddress.prototype.getIsRow=function(){
	this._recalculate(true, false);
	return this.bIsRow;
};
CellAddress.prototype.getCol=function(){
	this._recalculate(true, false);
	return this.col;
};
CellAddress.prototype.getCol0=function(){
	//0 - based
	this._recalculate(true, false);
	return this.col - 1;
};
CellAddress.prototype.getColAbs=function(){
	this._recalculate(true, false);
	return this.bColAbs;
};
CellAddress.prototype.getIsCol=function(){
	this._recalculate(true, false);
	return this.bIsCol;
};
CellAddress.prototype.getColLetter=function(){
	this._recalculate(false, true);
	return this.colLetter;
};
CellAddress.prototype.setRow=function(val){
	if( !(this.row >= 0 && this.row <= gc_nMaxRow) )
		this._valid = false;
	this._invalidId = true;
	this.row = val;
};
CellAddress.prototype.setCol=function(val){
	if( !(val >= 0 && val <= gc_nMaxCol) )
		return;
	this._invalidId = true;
	this.col = val;
};
CellAddress.prototype.setId=function(val){
	this._invalidCoord = true;
	this.id = val;
	this._checkId();
};
CellAddress.prototype.moveRow=function(diff){
	var val = this.row + diff;
	if( !(val >= 0 && val <= gc_nMaxRow) )
		return;
	this._invalidId = true;
	this.row = val;
};
CellAddress.prototype.moveCol=function(diff){
	var val = this.col + diff;
	if( !( val >= 0 && val <= gc_nMaxCol) )
		return;
	this._invalidId = true;
	this.col = val;
};

function isRealObject(obj)
{
    return obj !== null && typeof obj === "object";
}

  function FileStream(data, size)
  {
    this.obj = null;
    this.data = data;
    this.size = size;
    this.pos = 0;
    this.cur = 0;

    this.Seek = function(_pos)
    {
      if (_pos > this.size)
        return 1;
      this.pos = _pos;
      return 0;
    }
    this.Seek2 = function(_cur)
    {
      if (_cur > this.size)
        return 1;
      this.cur = _cur;
      return 0;
    }
    this.Skip = function(_skip)
    {
      if (_skip < 0)
        return 1;
      return this.Seek(this.pos + _skip);
    }
    this.Skip2 = function(_skip)
    {
      if (_skip < 0)
        return 1;
      return this.Seek2(this.cur + _skip);
    }

    // 1 bytes
    this.GetUChar = function()
    {
      if (this.cur >= this.size)
        return 0;
      return this.data[this.cur++];
    }
    this.GetBool = function()
    {
      if (this.cur >= this.size)
        return 0;
      return (this.data[this.cur++] == 1) ? true : false;
    }

    // 2 byte
    this.GetUShort = function()
    {
      if (this.cur + 1 >= this.size)
        return 0;
      return (this.data[this.cur++] | this.data[this.cur++] << 8);
    }

    // 4 byte
    this.GetULong = function()
    {
      if (this.cur + 3 >= this.size)
        return 0;
      var r =  (this.data[this.cur++] | this.data[this.cur++] << 8 | this.data[this.cur++] << 16 | this.data[this.cur++] << 24);
      if (r < 0)
        r += (0xFFFFFFFF + 1);
      return r;
    }

    this.GetLong = function()
    {
      if (this.cur + 3 >= this.size)
        return 0;
      return (this.data[this.cur++] | this.data[this.cur++] << 8 | this.data[this.cur++] << 16 | this.data[this.cur++] << 24);
    }

    //String
    this.GetString = function(len)
    {
      len *= 2;
      if (this.cur + len > this.size)
        return "";
      var t = "";
      for (var i = 0; i < len; i+=2)
      {
        var _c = this.data[this.cur + i + 1] << 8 | this.data[this.cur + i];
        if (_c == 0)
          break;

        t += String.fromCharCode(_c);
      }
      this.cur += len;
      return t;
    }
    this.GetString1 = function(len)
    {
      if (this.cur + len > this.size)
        return "";
      var t = "";
      for (var i = 0; i < len; i++)
      {
        var _c = this.data[this.cur + i];
        if (_c == 0)
          break;

        t += String.fromCharCode(_c);
      }
      this.cur += len;
      return t;
    }
    this.GetString2 = function()
    {
      var len = this.GetULong();
      return this.GetString(len);
    }

    this.GetString2A = function()
    {
      var len = this.GetULong();
      return this.GetString1(len);
    }

    this.EnterFrame = function(count)
    {
      if (this.pos >= this.size || this.size - this.pos < count)
        return 1;

      this.cur = this.pos;
      this.pos += count;
      return 0;
    }

    this.SkipRecord = function()
    {
      var _len = this.GetULong();
      this.Skip2(_len);
    }

    this.GetPercentage = function()
    {
      var s = this.GetString2();
      var _len = s.length;
      if (_len == 0)
        return null;

      var _ret = null;
      if ((_len - 1) == s.indexOf("%"))
      {
        s.substring(0, _len - 1);
        _ret = parseFloat(s);
        if (isNaN(_ret))
          _ret = null;
      }
      else
      {
        _ret = parseFloat(s);
        if (isNaN(_ret))
          _ret = null;
        else
          _ret /= 1000;
      }

      return _ret;
    }
  }
	function GetUTF16_fromUnicodeChar(code) {
		if (code < 0x10000) {
			return String.fromCharCode(code);
		} else {
			code -= 0x10000;
			return String.fromCharCode(0xD800 | ((code >> 10) & 0x03FF)) +
				String.fromCharCode(0xDC00 | (code & 0x03FF));
		}
	};
	function GetStringUtf8(reader, len) {
		if (reader.cur + len > reader.size) {
			return "";
		}
		var _res = "";

		var end = reader.cur + len;
		var val = 0;
		while (reader.cur < end) {
			var byteMain = reader.data[reader.cur];
			if (0x00 == (byteMain & 0x80)) {
				// 1 byte
				_res += GetUTF16_fromUnicodeChar(byteMain);
				++reader.cur;
			}
			else if (0x00 == (byteMain & 0x20)) {
				// 2 byte
				val = (((byteMain & 0x1F) << 6) |
				(reader.data[reader.cur + 1] & 0x3F));
				_res += GetUTF16_fromUnicodeChar(val);
				reader.cur += 2;
			}
			else if (0x00 == (byteMain & 0x10)) {
				// 3 byte
				val = (((byteMain & 0x0F) << 12) |
				((reader.data[reader.cur + 1] & 0x3F) << 6) |
				(reader.data[reader.cur + 2] & 0x3F));

				_res += GetUTF16_fromUnicodeChar(val);
				reader.cur += 3;
			}
			else if (0x00 == (byteMain & 0x08)) {
				// 4 byte
				val = (((byteMain & 0x07) << 18) |
				((reader.data[reader.cur + 1] & 0x3F) << 12) |
				((reader.data[reader.cur + 2] & 0x3F) << 6) |
				(reader.data[reader.cur + 3] & 0x3F));

				_res += GetUTF16_fromUnicodeChar(val);
				reader.cur += 4;
			}
			else if (0x00 == (byteMain & 0x04)) {
				// 5 byte
				val = (((byteMain & 0x03) << 24) |
				((reader.data[reader.cur + 1] & 0x3F) << 18) |
				((reader.data[reader.cur + 2] & 0x3F) << 12) |
				((reader.data[reader.cur + 3] & 0x3F) << 6) |
				(reader.data[reader.cur + 4] & 0x3F));

				_res += GetUTF16_fromUnicodeChar(val);
				reader.cur += 5;
			}
			else {
				// 6 byte
				val = (((byteMain & 0x01) << 30) |
				((reader.data[reader.cur + 1] & 0x3F) << 24) |
				((reader.data[reader.cur + 2] & 0x3F) << 18) |
				((reader.data[reader.cur + 3] & 0x3F) << 12) |
				((reader.data[reader.cur + 4] & 0x3F) << 6) |
				(reader.data[reader.cur + 5] & 0x3F));

				_res += GetUTF16_fromUnicodeChar(val);
				reader.cur += 6;
			}
		}

		return _res;
	};

  //----------------------------------------------------------export----------------------------------------------------
  window['AscCommon'] = window['AscCommon'] || {};
  window['AscCommon'].c_oSerConstants = c_oSerConstants;
  window['AscCommon'].c_oSerPropLenType = c_oSerPropLenType;
  window['AscCommon'].c_oSer_ColorType = c_oSer_ColorType;
  window['AscCommon'].c_oSerBorderType = c_oSerBorderType;
  window['AscCommon'].c_oSerBordersType = c_oSerBordersType;
  window['AscCommon'].c_oSerPaddingType = c_oSerPaddingType;
  window['AscCommon'].g_tabtype_left = 0;
  window['AscCommon'].g_tabtype_right = 1;
  window['AscCommon'].g_tabtype_center = 2;
  window['AscCommon'].g_tabtype_clear = 3;
  window['AscCommon'].BinaryCommonWriter = BinaryCommonWriter;
  window['AscCommon'].Binary_CommonReader = Binary_CommonReader;
  window['AscCommon'].FT_Stream2 = FT_Stream2;
  window['AscCommon'].gc_nMaxRow = gc_nMaxRow;
  window['AscCommon'].gc_nMaxCol = gc_nMaxCol;
  window['AscCommon'].gc_nMaxRow0 = gc_nMaxRow0;
  window['AscCommon'].gc_nMaxCol0 = gc_nMaxCol0;
  window['AscCommon'].g_oCellAddressUtils = g_oCellAddressUtils;
	window['AscCommon'].CellBase = CellBase;
  window['AscCommon'].CellAddress = CellAddress;
  window['AscCommon'].isRealObject = isRealObject;
  window['AscCommon'].FileStream = FileStream;
	window['AscCommon'].GetStringUtf8 = GetStringUtf8;
  window['AscCommon'].g_nodeAttributeStart = 0xFA;
  window['AscCommon'].g_nodeAttributeEnd = 0xFB;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function (window, undefined)
{
// Import
	var AscBrowser = AscCommon.AscBrowser;
	var locktype_None = AscCommon.locktype_None;
	var locktype_Mine = AscCommon.locktype_Mine;
	var locktype_Other = AscCommon.locktype_Other;
	var locktype_Other2 = AscCommon.locktype_Other2;
	var locktype_Other3 = AscCommon.locktype_Other3;
	var contentchanges_Add = AscCommon.contentchanges_Add;
	var CColor = AscCommon.CColor;
	var g_oCellAddressUtils = AscCommon.g_oCellAddressUtils;

	var c_oAscFileType = Asc.c_oAscFileType;

	if (typeof String.prototype.startsWith !== 'function')
	{
		String.prototype.startsWith = function (str)
		{
			return this.indexOf(str) === 0;
		};
		String.prototype['startsWith'] = String.prototype.startsWith;
	}
	if (typeof String.prototype.endsWith !== 'function')
	{
		String.prototype.endsWith = function (suffix)
		{
			return this.indexOf(suffix, this.length - suffix.length) !== -1;
		};
		String.prototype['endsWith'] = String.prototype.endsWith;
	}
	if (typeof String.prototype.repeat !== 'function')
	{
		String.prototype.repeat = function (count)
		{
			'use strict';
			if (this == null)
			{
				throw new TypeError('can\'t convert ' + this + ' to object');
			}
			var str = '' + this;
			count = +count;
			if (count != count)
			{
				count = 0;
			}
			if (count < 0)
			{
				throw new RangeError('repeat count must be non-negative');
			}
			if (count == Infinity)
			{
				throw new RangeError('repeat count must be less than infinity');
			}
			count = Math.floor(count);
			if (str.length == 0 || count == 0)
			{
				return '';
			}
			// Обеспечение того, что count является 31-битным целым числом, позволяет нам значительно
			// соптимизировать главную часть функции. Впрочем, большинство современных (на август
			// 2014 года) браузеров не обрабатывают строки, длиннее 1 << 28 символов, так что:
			if (str.length * count >= 1 << 28)
			{
				throw new RangeError('repeat count must not overflow maximum string size');
			}
			var rpt = '';
			for (; ;)
			{
				if ((count & 1) == 1)
				{
					rpt += str;
				}
				count >>>= 1;
				if (count == 0)
				{
					break;
				}
				str += str;
			}
			return rpt;
		};
		String.prototype['repeat'] = String.prototype.repeat;
	}
// Extend javascript String type
	String.prototype.strongMatch = function (regExp)
	{
		if (regExp && regExp instanceof RegExp)
		{
			var arr = this.toString().match(regExp);
			return !!(arr && arr.length > 0 && arr[0].length == this.length);
		}

		return false;
	};

	if (typeof require === 'function' && !window['XRegExp'])
	{
		window['XRegExp'] = require('xregexp');
	}

	var oZipImages = null;
	var sDownloadServiceLocalUrl = "../../../../downloadas";
	var sUploadServiceLocalUrl = "../../../../upload";
	var sUploadServiceLocalUrlOld = "../../../../uploadold";
	var sSaveFileLocalUrl = "../../../../savefile";
	var nMaxRequestLength = 5242880;//5mb <requestLimits maxAllowedContentLength="30000000" /> default 30mb

	function getSockJs()
	{
		return window['SockJS'] || require('sockjs');
	}
	function getJSZipUtils()
	{
		return window['JSZipUtils'] || require('jsziputils');
	}
	function getJSZip()
	{
		return window['JSZip'] || require('jszip');
	}

	function JSZipWrapper() {
		this.files = {};
	}

	JSZipWrapper.prototype.loadAsync = function(data, options) {
		var t = this;

		if (window["native"]) {
			return new Promise(function(resolve, reject) {

				var retFiles = null;
				if (options && options["base64"] === true)
					retFiles = window["native"]["ZipOpenBase64"](data);
				else
					retFiles = window["native"]["ZipOpen"](data);

				if (null != retFiles)
				{
					for (var id in retFiles) {
						t.files[id] = new JSZipObjectWrapper(retFiles[id]);
					}

					resolve(t);
				}
				else
				{
					reject(new Error("Failed archive"));
				}

			});
		}

		return AscCommon.getJSZip().loadAsync(data, options).then(function(zip){
			for (var id in zip.files) {
				t.files[id] = new JSZipObjectWrapper(zip.files[id]);
			}
			return t;
		});
	};
	JSZipWrapper.prototype.close = function() {
		if (window["native"])
			window["native"]["ZipClose"]();
	};

	function JSZipObjectWrapper(data) {
		this.data = data;
	}
	JSZipObjectWrapper.prototype.async = function(type) {

		if (window["native"]) {
			var t = this;

			return new Promise(function(resolve, reject) {

				var ret = window["native"]["ZipFileAsString"](t.data);

				if (null != ret)
				{
					resolve(ret);
				}
				else
				{
					reject(new Error("Failed file in archive"));
				}

			});
		}

		return this.data.async(type);
	};

	function getBaseUrl()
	{
		var indexHtml = window["location"]["href"];
		var questInd = indexHtml.indexOf("?");
    		if (questInd > 0)
		{
			indexHtml = indexHtml.substring(0, questInd);
		}
    		return indexHtml.substring(0, indexHtml.lastIndexOf("/") + 1);
	}

	function getEncodingParams()
	{
		var res = [];
		for (var i = 0; i < AscCommon.c_oAscEncodings.length; ++i)
		{
			var encoding = AscCommon.c_oAscEncodings[i];
			var newElem = {'codepage': encoding[0], 'lcid': encoding[1], 'name': encoding[3]};
			res.push(newElem);
		}
		return res;
	}

	function getEncodingByBOM(data) {
		var res = {encoding: AscCommon.c_oAscCodePageNone, size: 0};
		if (data.length >= 2) {
			res.size = 2;
			if (0xFF == data[0] && 0xFE == data[1]) {
				res.encoding = AscCommon.c_oAscCodePageUtf16;
			} else if (0xFE == data[0] && 0xFF == data[1]) {
				res.encoding = AscCommon.c_oAscCodePageUtf16BE;
			} else if (data.length >= 3) {
				res.size = 3;
				if (0xEF == data[0] && 0xBB == data[1] && 0xBF == data[2]) {
					res.encoding = AscCommon.c_oAscCodePageUtf8;
				} else if (data.length >= 4) {
					res.size = 4;
					if (0xFF == data[0] && 0xFE == data[1] && 0x00 == data[2] && 0x00 == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf32;
					} else if (0x00 == data[0] && 0x00 == data[1] && 0xFE == data[2] && 0xFF == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf32BE;
					} else if (0x2B == data[0] && 0x2F == data[1] && 0x76 == data[2] && 0x38 == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf7;
					} else if (0x2B == data[0] && 0x2F == data[1] && 0x76 == data[2] && 0x39 == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf7;
					} else if (0x2B == data[0] && 0x2F == data[1] && 0x76 == data[2] && 0x2B == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf7;
					} else if (0x2B == data[0] && 0x2F == data[1] && 0x76 == data[2] && 0x2F == data[3]) {
						res.encoding = AscCommon.c_oAscCodePageUtf7;
					}
				}
			}
		}
		return res;
	}

	function DocumentUrls()
	{
		this.urls = {};
		this.urlsReverse = {};
		this.documentUrl = "";
		this.imageCount = 0;
	}

	DocumentUrls.prototype = {
		mediaPrefix:     'media/',
		init:            function (urls)
						 {
							 this.addUrls(urls);
						 },
		getUrls:         function ()
						 {
							 return this.urls;
						 },
		addUrls:         function (urls)
						 {
							 for (var i in urls)
							 {
								 var url = urls[i];
								 this.urls[i] = url;
								 this.urlsReverse[url] = i;
								 this.imageCount++;
							 }

							 if (window["IS_NATIVE_EDITOR"])
							 {
								 window["native"]["setUrlsCount"](this.imageCount);
							 }
						 },
		addImageUrl:     function (strPath, url)
						 {
							 var urls = {};
							 urls[this.mediaPrefix + strPath] = url;
							 this.addUrls(urls);
						 },
		getImageUrl:     function (strPath)
						 {
							 return this.getUrl(this.mediaPrefix + strPath);
						 },
		getImageLocal:   function (url)
						 {
							 if(url && 0 === url.indexOf('data:image'))
							 {
								 return null;
							 }
							 var imageLocal = this.getLocal(url);
							 if (imageLocal && this.mediaPrefix == imageLocal.substring(0, this.mediaPrefix.length))
								 imageLocal = imageLocal.substring(this.mediaPrefix.length);
							 return imageLocal;
						 },
		imagePath2Local: function (imageLocal)
						 {
							 if (imageLocal && this.mediaPrefix == imageLocal.substring(0, this.mediaPrefix.length))
								 imageLocal = imageLocal.substring(this.mediaPrefix.length);
							 return imageLocal;
						 },
		getUrl:          function (strPath)
						 {
							 if (this.urls)
							 {
								 return this.urls[strPath];
							 }
							 return null;
						 },
		getLocal:        function (url)
						 {
							 if (this.urlsReverse)
							 {
								 var res = this.urlsReverse[url];
								 if (!res && typeof editor !== 'undefined' && editor.ThemeLoader && 0 == url.indexOf(editor.ThemeLoader.ThemesUrlAbs))
								 {
									 res = url.substring(editor.ThemeLoader.ThemesUrlAbs.length);
								 }
								 return res;
							 }
							 return null;
						 },
		getMaxIndex:     function (url)
						 {
							 return this.imageCount;
						 },
		getImageUrlsWithOtherExtention: function(imageLocal) {
			var res = [];
			var filename = GetFileName(imageLocal);
			for (var i in this.urls) {
				if (0 == i.indexOf(this.mediaPrefix + filename + '.') && this.mediaPrefix + imageLocal !== i) {
					res.push(this.urls[i]);
				}
			}
			return res;
		}
	};
	var g_oDocumentUrls = new DocumentUrls();

	function CHTMLCursor()
	{
		this.map = {};
		this.mapRetina = {};

		this.value = function(param)
		{
			var _map = this.map;
			if ((window["AscDesktopEditor"] && !AscCommon.AscBrowser.isMacOs) && AscCommon.AscBrowser.isRetina)
				_map = this.mapRetina;

			return _map[param] ? _map[param] : param;
		};

		this.register = function(type, url_ie, url_main, default_css_value)
		{
			if (AscBrowser.isIE)
			{
				var isTestRetinaNeed = (url_ie.lastIndexOf(".cur") == (url_ie.length - 4)) ? false : true;

				if (isTestRetinaNeed)
					this.map[type] = ("url(../../../../sdkjs/common/Images/" + url_ie + (AscBrowser.isRetina ? "_2x" : "") + ".cur), " + default_css_value);
				else
					this.map[type] = ("url(../../../../sdkjs/common/Images/" + url_ie + "), " + default_css_value);
			}
			else if (window.opera)
			{
				this.map[type] = default_css_value;
			}
			else
			{
				this.map[type] = ("url('../../../../sdkjs/common/Images/" + url_main[0] + ".png') " + url_main[1] + " " + url_main[2] + ", " + default_css_value);
                this.mapRetina[type] = ("url('../../../../sdkjs/common/Images/" + url_main[0] + "_2x.png') " + (url_main[1] << 1) + " " + (url_main[2] << 1) + ", " + default_css_value);
			}
		};
	}

	function OpenFileResult()
	{
		this.bSerFormat = false;
		this.data = null;
		this.url = null;
		this.changes = null;
	}

	function saveWithParts(fSendCommand, fCallback, fCallbackRequest, oAdditionalData, dataContainer)
	{
		var index = dataContainer.index;
		if (null == dataContainer.part && (!dataContainer.data || dataContainer.data.length <= nMaxRequestLength))
		{
			oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.CompleteAll;
		}
		else
		{
			if (0 == index)
			{
				oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.PartStart;
				dataContainer.count = Math.ceil(dataContainer.data.length / nMaxRequestLength);
			}
			else if (index != dataContainer.count - 1)
			{
				oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.Part;
			}
			else
			{
				oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.Complete;
			}
			if(typeof dataContainer.data === 'string') {
				dataContainer.part = dataContainer.data.substring(index * nMaxRequestLength, (index + 1) * nMaxRequestLength);
			} else {
				dataContainer.part = dataContainer.data.subarray(index * nMaxRequestLength, (index + 1) * nMaxRequestLength);
			}
		}
		dataContainer.index++;
		oAdditionalData["saveindex"] = dataContainer.index;
		fSendCommand(function (incomeObject)
		{
			if (null != incomeObject && "ok" == incomeObject["status"])
			{
				if (dataContainer.index < dataContainer.count)
				{
					oAdditionalData["savekey"] = incomeObject["data"];
					saveWithParts(fSendCommand, fCallback, fCallbackRequest, oAdditionalData, dataContainer);
				}
				else if (fCallbackRequest)
				{
					fCallbackRequest(incomeObject);
				}
			}
			else
			{
				fCallbackRequest ? fCallbackRequest(incomeObject) : fCallback(incomeObject);
			}
		}, oAdditionalData, dataContainer);
	}

	function loadFileContent(url, callback, opt_responseType)
	{
		asc_ajax({
			url:      url,
			dataType: "text",
			responseType: opt_responseType,
			success:  callback,
			error:    function ()
					  {
						  callback(null);
					  }
		});
	}

	function getImageFromChanges(name)
	{
		var content;
		var ext = GetFileExtension(name);
		if (null !== ext && oZipImages && (content = oZipImages[name]))
		{
			return 'data:image/' + ext + ';base64,' + AscCommon.Base64Encode(content, content.length, 0);
		}
		return null;
	}

	function initStreamFromResponse(httpRequest) {
		var stream;
		if (typeof ArrayBuffer !== 'undefined') {
			stream = new Uint8Array(httpRequest.response);
		} else if (AscCommon.AscBrowser.isIE) {
			var _response = new VBArray(httpRequest["responseBody"]).toArray();

			var srcLen = _response.length;
			var pointer = g_memory.Alloc(srcLen);
			var tempStream = new AscCommon.FT_Stream2(pointer.data, srcLen);
			tempStream.obj = pointer.obj;

			stream = tempStream.data;
			var index = 0;

			while (index < srcLen)
			{
				stream[index] = _response[index];
				index++;
			}
		}
		return stream;
	}
	function checkStreamSignature(stream, Signature) {
		if (stream.length > Signature.length) {
			for(var i = 0 ; i < Signature.length; ++i){
				if(stream[i] !== Signature.charCodeAt(i)){
					return false;
				}
			}
			return true;
		}
		return false;
	}
	function openFileCommand(binUrl, changesUrl, Signature, callback)
	{
		var bError = false, oResult = new OpenFileResult(), bEndLoadFile = false, bEndLoadChanges = false;
		var onEndOpen = function ()
		{
			if (bEndLoadFile && bEndLoadChanges)
			{
				if (callback)
				{
					callback(bError, oResult);
				}
			}
		};
		var sFileUrl = binUrl;
		sFileUrl = sFileUrl.replace(/\\/g, "/");

		if (!window['IS_NATIVE_EDITOR'])
		{
			loadFileContent(sFileUrl, function (httpRequest) {
					//получаем url к папке с файлом
					var url;
					var nIndex = sFileUrl.lastIndexOf("/");
					url = (-1 !== nIndex) ? sFileUrl.substring(0, nIndex + 1) : sFileUrl;
					if (httpRequest)
					{
						var stream = initStreamFromResponse(httpRequest);
						if (stream) {
							oResult.bSerFormat = checkStreamSignature(stream, Signature);
							oResult.data = stream;
						} else {
							bError = true;
						}
					}
					else
					{
						bError = true;
					}
					bEndLoadFile = true;
					onEndOpen();
				}, "arraybuffer");
		}

		if (changesUrl)
		{
			oZipImages = {};
			getJSZipUtils().getBinaryContent(changesUrl, function (err, data)
			{
				if (err)
				{
					bEndLoadChanges = true;
					bError = true;
					onEndOpen();
					return;
				}

				oResult.changes = [];
				getJSZip().loadAsync(data).then(function (zipChanges)
				{
					var relativePaths = [];
					var promises = [];
					zipChanges.forEach(function (relativePath, file)
					{
						relativePaths.push(relativePath);
						promises.push(file.async(relativePath.endsWith('.json') ? 'string' : 'uint8array'));
					});
					Promise.all(promises).then(function (values)
					{
						var relativePath;
						for (var i = 0; i < values.length; ++i)
						{
							if ((relativePath = relativePaths[i]).endsWith('.json'))
							{
								oResult.changes[parseInt(relativePath.slice('changes'.length))] = JSON.parse(values[i]);
							}
							else
							{
								oZipImages[relativePath] = values[i];
							}
						}
						bEndLoadChanges = true;
						onEndOpen();
					});
				});
			});
		}
		else
		{
			oZipImages = null;
			bEndLoadChanges = true;
		}

		if (window['IS_NATIVE_EDITOR'])
		{
			var stream = window["native"]["openFileCommand"](sFileUrl, changesUrl, Signature);
 
            //получаем url к папке с файлом
            var url;
            var nIndex = sFileUrl.lastIndexOf("/");
            url = (-1 !== nIndex) ? sFileUrl.substring(0, nIndex + 1) : sFileUrl;

            if (stream) {
                oResult.bSerFormat = checkStreamSignature(stream, Signature);
				oResult.data = stream;
            } else {
                bError = true;
            }
 
            bEndLoadFile = true;
            onEndOpen();
		}
	}

	function sendCommand(editor, fCallback, rdata, dataContainer)
	{
		//json не должен превышать размера 2097152, иначе при его чтении будет exception
		var docConnectionId = editor.CoAuthoringApi.getDocId();
		if (docConnectionId && docConnectionId !== rdata["id"])
		{
			//на случай если поменялся documentId в Version History
			rdata['docconnectionid'] = docConnectionId;
		}
		if (null == rdata["savetype"])
		{
			editor.CoAuthoringApi.openDocument(rdata);
			return;
		}
		rdata["userconnectionid"] = editor.CoAuthoringApi.getUserConnectionId();
		asc_ajax({
			type:        'POST',
			url:         sDownloadServiceLocalUrl + '/' + rdata["id"] + '?cmd=' + encodeURIComponent(JSON.stringify(rdata)),
			data:        dataContainer.part || dataContainer.data,
			contentType: "application/octet-stream",
			error:       function ()
						 {
							 if (fCallback)
							 {
								 fCallback(null, true);
							 }
						 },
			success:     function (httpRequest)
						 {
							 if (fCallback)
							 {
								 fCallback(JSON.parse(httpRequest.responseText), true);
							 }
						 }
		});
	}

	function sendSaveFile(docId, userId, title, jwt, data, fError, fsuccess)
	{
		var cmd = {'id': docId, "userid": userId, "jwt": jwt, 'outputpath': title};
		asc_ajax({
			type:        'POST',
			url:         sSaveFileLocalUrl + '/' + docId + '?cmd=' + encodeURIComponent(JSON.stringify(cmd)),
			data:        data,
			contentType: "application/octet-stream",
			error:       fError,
			success:     fsuccess
		});
	}

	function mapAscServerErrorToAscError(nServerError, nAction)
	{
		var nRes = Asc.c_oAscError.ID.Unknown;
		switch (nServerError)
		{
			case c_oAscServerError.NoError :
				nRes = Asc.c_oAscError.ID.No;
				break;
			case c_oAscServerError.TaskQueue :
			case c_oAscServerError.TaskResult :
				nRes = Asc.c_oAscError.ID.Database;
				break;
			case c_oAscServerError.ConvertDownload :
				nRes = Asc.c_oAscError.ID.DownloadError;
				break;
			case c_oAscServerError.ConvertTimeout :
			case c_oAscServerError.ConvertDeadLetter :
				nRes = Asc.c_oAscError.ID.ConvertationTimeout;
				break;
			case c_oAscServerError.ConvertDRM :
			case c_oAscServerError.ConvertPASSWORD :
				nRes = Asc.c_oAscError.ID.ConvertationPassword;
				break;
			case c_oAscServerError.ConvertLIMITS :
			case c_oAscServerError.ConvertCONVERT_CORRUPTED :
			case c_oAscServerError.ConvertLIBREOFFICE :
			case c_oAscServerError.ConvertPARAMS :
			case c_oAscServerError.ConvertNEED_PARAMS :
			case c_oAscServerError.ConvertUnknownFormat :
			case c_oAscServerError.ConvertReadFile :
			case c_oAscServerError.Convert :
				nRes =
					AscCommon.c_oAscAdvancedOptionsAction.Save === nAction ? Asc.c_oAscError.ID.ConvertationSaveError :
						Asc.c_oAscError.ID.ConvertationOpenError;
				break;
			case c_oAscServerError.UploadContentLength :
				nRes = Asc.c_oAscError.ID.UplImageSize;
				break;
			case c_oAscServerError.UploadExtension :
				nRes = Asc.c_oAscError.ID.UplImageExt;
				break;
			case c_oAscServerError.UploadCountFiles :
				nRes = Asc.c_oAscError.ID.UplImageFileCount;
				break;
			case c_oAscServerError.UploadURL :
				nRes = Asc.c_oAscError.ID.UplImageUrl;
				break;
			case c_oAscServerError.VKey :
				nRes = Asc.c_oAscError.ID.FileVKey;
				break;
			case c_oAscServerError.VKeyEncrypt :
				nRes = Asc.c_oAscError.ID.VKeyEncrypt;
				break;
			case c_oAscServerError.VKeyKeyExpire :
				nRes = Asc.c_oAscError.ID.KeyExpire;
				break;
			case c_oAscServerError.VKeyUserCountExceed :
				nRes = Asc.c_oAscError.ID.UserCountExceed;
				break;
			case c_oAscServerError.Storage :
			case c_oAscServerError.StorageFileNoFound :
			case c_oAscServerError.StorageRead :
			case c_oAscServerError.StorageWrite :
			case c_oAscServerError.StorageRemoveDir :
			case c_oAscServerError.StorageCreateDir :
			case c_oAscServerError.StorageGetInfo :
			case c_oAscServerError.Upload :
			case c_oAscServerError.ReadRequestStream :
			case c_oAscServerError.Unknown :
				nRes = Asc.c_oAscError.ID.Unknown;
				break;
		}
		return nRes;
	}

	function joinUrls(base, relative)
	{
		//http://stackoverflow.com/questions/14780350/convert-relative-path-to-absolute-using-javascript
		var stack = base.split("/"),
			parts = relative.split("/");
		stack.pop(); // remove current file name (or empty string)
					 // (omit if "base" is the current folder without trailing slash)
		for (var i = 0; i < parts.length; i++)
		{
			if (parts[i] == ".")
				continue;
			if (parts[i] == "..")
				stack.pop();
			else
				stack.push(parts[i]);
		}
		return stack.join("/");
	}

	function getFullImageSrc2(src)
	{
		if (window["NATIVE_EDITOR_ENJINE"])
			return src;

		var start = src.slice(0, 6);
		if (0 === start.indexOf('theme') && editor.ThemeLoader)
		{
			return editor.ThemeLoader.ThemesUrlAbs + src;
		}

		if (0 !== start.indexOf('http:') && 0 !== start.indexOf('data:') && 0 !== start.indexOf('https:') &&
			0 !== start.indexOf('file:') && 0 !== start.indexOf('ftp:'))
		{
			var srcFull = g_oDocumentUrls.getImageUrl(src);
			if (srcFull)
			{
				return srcFull;
			}
		}
		return src;
	}

	function fSortAscending(a, b)
	{
		return a - b;
	}

	function fSortDescending(a, b)
	{
		return b - a;
	}

	function isLeadingSurrogateChar(nCharCode)
	{
		return (nCharCode >= 0xD800 && nCharCode <= 0xDFFF);
	}

	function decodeSurrogateChar(nLeadingChar, nTrailingChar)
	{
		if (nLeadingChar < 0xDC00 && nTrailingChar >= 0xDC00 && nTrailingChar <= 0xDFFF)
			return 0x10000 + ((nLeadingChar & 0x3FF) << 10) | (nTrailingChar & 0x3FF);
		else
			return null;
	}

	function encodeSurrogateChar(nUnicode)
	{
		if (nUnicode < 0x10000)
		{
			return String.fromCharCode(nUnicode);
		}
		else
		{
			nUnicode = nUnicode - 0x10000;
			var nLeadingChar = 0xD800 | (nUnicode >> 10);
			var nTrailingChar = 0xDC00 | (nUnicode & 0x3FF);
			return String.fromCharCode(nLeadingChar) + String.fromCharCode(nTrailingChar);
		}
	}

	function convertUnicodeToUTF16(sUnicode)
	{
		var sUTF16 = "";
		var nLength = sUnicode.length;
		for (var nPos = 0; nPos < nLength; nPos++)
		{
			sUTF16 += encodeSurrogateChar(sUnicode[nPos]);
		}

		return sUTF16;
	}

	function convertUTF16toUnicode(sUTF16)
	{
		var sUnicode = [];
		var nLength = sUTF16.length;
		for (var nPos = 0; nPos < nLength; nPos++)
		{
			var nUnicode = null;
			var nCharCode = sUTF16.charCodeAt(nPos);
			if (isLeadingSurrogateChar(nCharCode))
			{
				if (nPos + 1 < nLength)
				{
					nPos++;
					var nTrailingChar = sUTF16.charCodeAt(nPos);
					nUnicode = decodeSurrogateChar(nCharCode, nTrailingChar);
				}
			}
			else
				nUnicode = nCharCode;

			if (null !== nUnicode)
				sUnicode.push(nUnicode);
		}

		return sUnicode;
	}

    function CUnicodeIterator(str)
    {
        this._position = 0;
        this._index = 0;
        this._str = str;
    }
    CUnicodeIterator.prototype =
	{
		isOutside : function()
		{
			return (this._index >= this._str.length);
		},
		isInside : function()
		{
			return (this._index < this._str.length);
		},
		value : function()
		{
			if (this._index >= this._str.length)
				return 0;

			var nCharCode = this._str.charCodeAt(this._index);
			if (!AscCommon.isLeadingSurrogateChar(nCharCode))
				return nCharCode;

			if ((this._str.length - 1) == this._index)
				return nCharCode; // error

			var nTrailingChar = this._str.charCodeAt(this._index + 1);
			return AscCommon.decodeSurrogateChar(nCharCode, nTrailingChar);
		},
		next : function()
		{
			if (this._index >= this._str.length)
				return;

			this._position++;
			if (!AscCommon.isLeadingSurrogateChar(this._str.charCodeAt(this._index)))
			{
				++this._index;
				return;
			}

			if (this._index == (this._str.length - 1))
			{
				++this._index;
				return;
			}

			this._index += 2;
		},
		position : function()
		{
			return this._position;
		}
	};

    CUnicodeIterator.prototype.check = CUnicodeIterator.prototype.isInside;

    /**
	 * @returns {CUnicodeIterator}
     */
    String.prototype.getUnicodeIterator = function()
    {
        return new CUnicodeIterator(this);
    };

	function test_ws_name2()
	{
		var str_namedRanges      = "[A-Z\u005F\u0080-\u0081\u0083\u0085-\u0087\u0089-\u008A\u008C-\u0091\u0093-\u0094\u0096-\u0097\u0099-\u009A\u009C-\u009F\u00A1-\u00A5\u00A7-\u00A8\u00AA\u00AD\u00AF-\u00BA\u00BC-\u02B8\u02BB-\u02C1\u02C7\u02C9-\u02CB\u02CD\u02D0-\u02D1\u02D8-\u02DB\u02DD\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0621-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4-\u07F5\u07FA\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0972\u097B-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D3D\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E3A\u0E40-\u0E4E\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDD\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8B\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10D0-\u10FA\u10FC\u1100-\u1159\u115F-\u11A2\u11A8-\u11F9\u1200-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u1676\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19A9\u19C1-\u19C7\u1A00-\u1A16\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2010\u2013-\u2016\u2018\u201C-\u201D\u2020-\u2021\u2025-\u2027\u2030\u2032-\u2033\u2035\u203B\u2071\u2074\u207F\u2081-\u2084\u2090-\u2094\u2102-\u2103\u2105\u2107\u2109-\u2113\u2115-\u2116\u2119-\u211D\u2121-\u2122\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2153-\u2154\u215B-\u215E\u2160-\u2188\u2190-\u2199\u21D2\u21D4\u2200\u2202-\u2203\u2207-\u2208\u220B\u220F\u2211\u2215\u221A\u221D-\u2220\u2223\u2225\u2227-\u222C\u222E\u2234-\u2237\u223C-\u223D\u2248\u224C\u2252\u2260-\u2261\u2264-\u2267\u226A-\u226B\u226E-\u226F\u2282-\u2283\u2286-\u2287\u2295\u2299\u22A5\u22BF\u2312\u2460-\u24B5\u24D0-\u24E9\u2500-\u254B\u2550-\u2574\u2581-\u258F\u2592-\u2595\u25A0-\u25A1\u25A3-\u25A9\u25B2-\u25B3\u25B6-\u25B7\u25BC-\u25BD\u25C0-\u25C1\u25C6-\u25C8\u25CB\u25CE-\u25D1\u25E2-\u25E5\u25EF\u2605-\u2606\u2609\u260E-\u260F\u261C\u261E\u2640\u2642\u2660-\u2661\u2663-\u2665\u2667-\u266A\u266C-\u266D\u266F\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C6F\u2C71-\u2C7D\u2C80-\u2CE4\u2D00-\u2D25\u2D30-\u2D65\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3000-\u3003\u3005-\u3017\u301D-\u301F\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31B7\u31F0-\u321C\u3220-\u3229\u3231-\u3232\u3239\u3260-\u327B\u327F\u32A3-\u32A8\u3303\u330D\u3314\u3318\u3322-\u3323\u3326-\u3327\u332B\u3336\u333B\u3349-\u334A\u334D\u3351\u3357\u337B-\u337E\u3380-\u3384\u3388-\u33CA\u33CD-\u33D3\u33D5-\u33D6\u33D8\u33DB-\u33DD\u3400-\u4DB5\u4E00-\u9FC3\uA000-\uA48C\uA500-\uA60C\uA610-\uA61F\uA62A-\uA62B\uA640-\uA65F\uA662-\uA66E\uA680-\uA697\uA722-\uA787\uA78B-\uA78C\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA90A-\uA925\uA930-\uA946\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAC00-\uD7A3\uE000-\uF848\uF900-\uFA2D\uFA30-\uFA6A\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE30-\uFE31\uFE33-\uFE44\uFE49-\uFE52\uFE54-\uFE57\uFE59-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFF01-\uFF5E\uFF61-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6]",
			str_namedSheetsRange = "\u0001-\u0026\u0028-\u0029\u002B-\u002D\u003B-\u003E\u0040\u005E\u0060\u007B-\u007F\u0082\u0084\u008B\u0092\u0095\u0098\u009B\u00A0\u00A6\u00A9\u00AB-\u00AC\u00AE\u00BB\u0378-\u0379\u037E-\u0383\u0387\u038B\u038D\u03A2\u0524-\u0530\u0557-\u0558\u055A-\u0560\u0588-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EF\u05F3-\u05FF\u0604-\u0605\u0609-\u060A\u060C-\u060D\u061B-\u061E\u0620\u065F\u066A-\u066D\u06D4\u0700-\u070E\u074B-\u074C\u07B2-\u07BF\u07F7-\u07F9\u07FB-\u0900\u093A-\u093B\u094E-\u094F\u0955-\u0957\u0964-\u0965\u0970\u0973-\u097A\u0980\u0984\u098D-\u098E\u0991-\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BB\u09C5-\u09C6\u09C9-\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4-\u09E5\u09FB-\u0A00\u0A04\u0A0B-\u0A0E\u0A11-\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A3B\u0A3D\u0A43-\u0A46\u0A49-\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABB\u0AC6\u0ACA\u0ACE-\u0ACF\u0AD1-\u0ADF\u0AE4-\u0AE5\u0AF0\u0AF2-\u0B00\u0B04\u0B0D-\u0B0E\u0B11-\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3B\u0B45-\u0B46\u0B49-\u0B4A\u0B4E-\u0B55\u0B58-\u0B5B\u0B5E\u0B64-\u0B65\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE-\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BFB-\u0C00\u0C04\u0C0D\u0C11\u0C29\u0C34\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5A-\u0C5F\u0C64-\u0C65\u0C70-\u0C77\u0C80-\u0C81\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4-\u0CE5\u0CF0\u0CF3-\u0D01\u0D04\u0D0D\u0D11\u0D29\u0D3A-\u0D3C\u0D45\u0D49\u0D4E-\u0D56\u0D58-\u0D5F\u0D64-\u0D65\u0D76-\u0D78\u0D80-\u0D81\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE-\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3E\u0E4F\u0E5A-\u0E80\u0E83\u0E85-\u0E86\u0E89\u0E8B-\u0E8C\u0E8E-\u0E93\u0E98\u0EA0\u0EA4\u0EA6\u0EA8-\u0EA9\u0EAC\u0EBA\u0EBE-\u0EBF\u0EC5\u0EC7\u0ECE-\u0ECF\u0EDA-\u0EDB\u0EDE-\u0EFF\u0F04-\u0F12\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F8C-\u0F8F\u0F98\u0FBD\u0FCD\u0FD0-\u0FFF\u104A-\u104F\u109A-\u109D\u10C6-\u10CF\u10FB\u10FD-\u10FF\u115A-\u115E\u11A3-\u11A7\u11FA-\u11FF\u1249\u124E-\u124F\u1257\u1259\u125E-\u125F\u1289\u128E-\u128F\u12B1\u12B6-\u12B7\u12BF\u12C1\u12C6-\u12C7\u12D7\u1311\u1316-\u1317\u135B-\u135E\u1361-\u1368\u137D-\u137F\u139A-\u139F\u13F5-\u1400\u166D-\u166E\u1677-\u167F\u169B-\u169F\u16EB-\u16ED\u16F1-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DA\u17DE-\u17DF\u17EA-\u17EF\u17FA-\u180A\u180F\u181A-\u181F\u1878-\u187F\u18AB-\u18FF\u191D-\u191F\u192C-\u192F\u193C-\u193F\u1941-\u1945\u196E-\u196F\u1975-\u197F\u19AA-\u19AF\u19CA-\u19CF\u19DA-\u19DF\u1A1C-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BAB-\u1BAD\u1BBA-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E-\u1CFF\u1DE7-\u1DFD\u1F16-\u1F17\u1F1E-\u1F1F\u1F46-\u1F47\u1F4E-\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E-\u1F7F\u1FB5\u1FC5\u1FD4-\u1FD5\u1FDC\u1FF0-\u1FF1\u1FF5\u1FFF\u2011-\u2012\u2017\u2019-\u201B\u201E-\u201F\u2022-\u2024\u2031\u2034\u2036-\u203A\u203C-\u2043\u2045-\u2051\u2053-\u205E\u2065-\u2069\u2072-\u2073\u207D-\u207E\u208D-\u208F\u2095-\u209F\u20B6-\u20CF\u20F1-\u20FF\u2150-\u2152\u2189-\u218F\u2329-\u232A\u23E8-\u23FF\u2427-\u243F\u244B-\u245F\u269E-\u269F\u26BD-\u26BF\u26C4-\u2700\u2705\u270A-\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u275F-\u2760\u2768-\u2775\u2795-\u2797\u27B0\u27BF\u27C5-\u27C6\u27CB\u27CD-\u27CF\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC-\u29FD\u2B4D-\u2B4F\u2B55-\u2BFF\u2C2F\u2C5F\u2C70\u2C7E-\u2C7F\u2CEB-\u2CFC\u2CFE-\u2CFF\u2D26-\u2D2F\u2D66-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u2FFF\u3018-\u301C\u3030\u303D\u3040\u3097-\u3098\u30A0\u3100-\u3104\u312E-\u3130\u318F\u31B8-\u31BF\u31E4-\u31EF\u321F\u3244-\u324F\u32FF\u4DB6-\u4DBF\u9FC4-\u9FFF\uA48D-\uA48F\uA4C7-\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA660-\uA661\uA673-\uA67B\uA67E\uA698-\uA6FF\uA78D-\uA7FA\uA82C-\uA83F\uA874-\uA87F\uA8C5-\uA8CF\uA8DA-\uA8FF\uA92F\uA954-\uA9FF\uAA37-\uAA3F\uAA4E-\uAA4F\uAA5A-\uABFF\uD7A4-\uD7FF\uFA2E-\uFA2F\uFA6B-\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90-\uFD91\uFDC8-\uFDEF\uFDFE-\uFDFF\uFE10-\uFE1F\uFE27-\uFE2F\uFE32\uFE45-\uFE48\uFE53\uFE58\uFE67\uFE6C-\uFE6F\uFE75\uFEFD-\uFEFE\uFF00\uFF5F-\uFF60\uFFBF-\uFFC1\uFFC8-\uFFC9\uFFD0-\uFFD1\uFFD8-\uFFD9\uFFDD-\uFFDF\uFFE7\uFFEF-\uFFF8\uFFFE-\uFFFF",
			str_operator         = ",\\s-+/^&%<=>",
			str_excludeCharts    = "'*\\[\\]\\:/?";

		this.regExp_namedRanges = new RegExp(str_namedRanges, "i");
		this.regExp_namedSheetsRange = new RegExp("[" + str_namedSheetsRange + "]", "ig");
//    /[-+*\/^&%<=>:]/,
		this.regExp_strOperator = new RegExp("[" + str_operator + "]", "ig");
		this.regExp_strExcludeCharts = new RegExp("[" + str_excludeCharts + "]", "ig");

		this.test = function (str)
		{
			var ch1 = str.substr(0, 1);

			this.regExp_strExcludeCharts.lastIndex = 0;
			this.regExp_namedRanges.lastIndex = 0;
			this.regExp_namedSheetsRange.lastIndex = 0;
			this.regExp_strOperator.lastIndex = 0;

			if (this.regExp_strExcludeCharts.test(str))
			{//если содержутся недопустимые символы.
				return undefined;
			}

			if (!this.regExp_namedRanges.test(ch1))
			{//если первый символ находится не в str_namedRanges, то однозначно надо экранировать
				return false;
			}
			else
			{
				if (this.regExp_namedSheetsRange.test(str) || this.regExp_strOperator.test(str))
				{//первый символ допустимый. проверяем всю строку на наличие символов, с которыми необходимо экранировать
					return false;
				}
				//проверка на то, что название листа не совпадает с допустимым адресом ячейки, как в A1 так и RC стилях.
				var match = str.match(rx_ref);
				if (match != null)
				{
					var m1 = match[1], m2 = match[2];
					if (match.length >= 3 && g_oCellAddressUtils.colstrToColnum(m1.substr(0, (m1.length - m2.length))) <= AscCommon.gc_nMaxCol && parseInt(m2) <= AscCommon.gc_nMaxRow)
					{
						return false;
					}
				}
				return true;
			}
		};

		return this;

	}

	function test_defName()
	{
		var nameRangeRE = new RegExp("(^([" + str_namedRanges + "_])([" + str_namedRanges + "_0-9]*)$)", "i");

		this.test = function (str)
		{
			var match, m1, m2;
			if (!nameRangeRE.test(str))
			{
				return false;
			}

			match = str.match(rx_ref);
			if (match != null)
			{
				m1 = match[1];
				m2 = match[2];
				if (match.length >= 3 && g_oCellAddressUtils.colstrToColnum(m1.substr(0, (m1.length - m2.length))) <= AscCommon.gc_nMaxCol && parseInt(m2) <= AscCommon.gc_nMaxRow)
				{
					return false;
				}
			}

			return true;
		};

		return this;
	}

	var cStrucTableReservedWords = {
		all: "#All", data: "#Data", headers: "#Headers", totals: "#Totals", thisrow: "#This Row", at: "@"
	};
	var FormulaTablePartInfo = {
		all:     1,
		data:    2,
		headers: 3,
		totals:  4,
		thisRow: 5,
		columns: 6
	};

	var cStrucTableLocalColumns = null;
	var cBoolOrigin = {'t': 'TRUE', 'f': 'FALSE'};
	var cBoolLocal = {};
	var cErrorOrigin = {
		"nil": "#NULL!",
		"div": "#DIV\/0!",
		"value": "#VALUE!",
		"ref": "#REF!",
		"name": "#NAME?",
		"num": "#NUM!",
		"na": "#N\/A",
		"getdata": "#GETTING_DATA",
		"uf": "#UNSUPPORTED_FUNCTION!"
	};
	var cErrorLocal = {};

	function build_local_rx(data)
	{
		rx_table_local = build_rx_table(data ? data["StructureTables"] : null);
		rx_bool_local = build_rx_bool((data && data["CONST_TRUE_FALSE"]) || cBoolOrigin);
		rx_error_local = build_rx_error(data ? data["CONST_ERROR"] : null);
	}

	function build_rx_table(local)
	{
		cStrucTableLocalColumns = ( local ? local : {
			"h":  "Headers",
			"d":  "Data",
			"a":  "All",
			"tr": "This Row",
			"t":  "Totals"
		} );
		return build_rx_table_cur();
	}

	function build_rx_table_cur()
	{
		var loc_all                          = cStrucTableLocalColumns['a'],
			loc_headers                      = cStrucTableLocalColumns['h'],
			loc_data                         = cStrucTableLocalColumns['d'],
			loc_totals                       = cStrucTableLocalColumns['t'],
			loc_this_row                     = cStrucTableLocalColumns['tr'],
			structured_tables_headata        = new XRegExp('(?:\\[\\#' + loc_headers + '\\]\\' + FormulaSeparators.functionArgumentSeparator + '\\[\\#' + loc_data + '\\])'),
			structured_tables_datals         = new XRegExp('(?:\\[\\#' + loc_data + '\\]\\' + FormulaSeparators.functionArgumentSeparator + '\\[\\#' + loc_totals + '\\])'),
			structured_tables_userColumn     = new XRegExp('(?:\'\\[|\'\\]|[^[\\]])+'),
			structured_tables_reservedColumn = new XRegExp('\\#(?:' + loc_all + '|' + loc_headers + '|' + loc_totals + '|' + loc_data + '|' + loc_this_row + ')|@');

		return XRegExp.build('^(?<tableName>{{tableName}})\\[(?<columnName>{{columnName}})?\\]', {
			"tableName":  new XRegExp("^(:?[" + str_namedRanges + "][" + str_namedRanges + "\\d.]*)"),
			"columnName": XRegExp.build('(?<reservedColumn>{{reservedColumn}})|(?<oneColumn>{{userColumn}})|(?<columnRange>{{userColumnRange}})|(?<hdtcc>{{hdtcc}})', {
				"userColumn":      structured_tables_userColumn,
				"reservedColumn":  structured_tables_reservedColumn,
				"userColumnRange": XRegExp.build('\\[(?<colStart>{{uc}})\\]\\:\\[(?<colEnd>{{uc}})\\]', {
					"uc": structured_tables_userColumn
				}),
				"hdtcc":           XRegExp.build('(?<hdt>\\[{{rc}}\\]|{{hd}}|{{dt}})(?:\\' + FormulaSeparators.functionArgumentSeparator + '(?:\\[(?<hdtcstart>{{uc}})\\])(?:\\:(?:\\[(?<hdtcend>{{uc}})\\]))?)?', {
					"rc": structured_tables_reservedColumn,
					"hd": structured_tables_headata,
					"dt": structured_tables_datals,
					"uc": structured_tables_userColumn
				})
			})
		}, 'i');
	}

	function build_rx_bool(local)
	{
		var t = cBoolLocal.t = local['t'].toUpperCase();
		var f = cBoolLocal.f = local['f'].toUpperCase();

		return new RegExp("^(" + t + "|" + f + ")([-+*\\/^&%<=>: ;),}]|$)", "i");
	}

	function build_rx_error(local)
	{
		// ToDo переделать на более правильную реализацию. Не особо правильное копирование
		local = local ? local : {
			"nil":     "#NULL!",
			"div":     "#DIV\/0!",
			"value":   "#VALUE!",
			"ref":     "#REF!",
			"name":    "#NAME\\?",
			"num":     "#NUM!",
			"na":      "#N\/A",
			"getdata": "#GETTING_DATA",
			"uf":      "#UNSUPPORTED_FUNCTION!"
		};
		cErrorLocal['nil'] = local['nil'];
		cErrorLocal['div'] = local['div'];
		cErrorLocal['value'] = local['value'];
		cErrorLocal['ref'] = local['ref'];
		cErrorLocal['name'] = local['name'];
		cErrorLocal['num'] = local['num'];
		cErrorLocal['na'] = local['na'];
		cErrorLocal['getdata'] = local['getdata'];
		cErrorLocal['uf'] = local['uf'];

		return new RegExp("^(" + cErrorLocal["nil"] + "|" +
			cErrorLocal["div"] + "|" +
			cErrorLocal["value"] + "|" +
			cErrorLocal["ref"] + "|" +
			cErrorLocal["name"] + "|" +
			cErrorLocal["num"] + "|" +
			cErrorLocal["na"] + "|" +
			cErrorLocal["getdata"] + "|" +
			cErrorLocal["uf"] + ")", "i");
	}

	var PostMessageType = {
		UploadImage:    0,
		ExtensionExist: 1
	};

	var c_oAscServerError = {
		NoError:           0,
		Unknown:           -1,
		ReadRequestStream: -3,

		TaskQueue: -20,

		TaskResult: -40,

		Storage:            -60,
		StorageFileNoFound: -61,
		StorageRead:        -62,
		StorageWrite:       -63,
		StorageRemoveDir:   -64,
		StorageCreateDir:   -65,
		StorageGetInfo:     -66,

		Convert:                  -80,
		ConvertDownload:          -81,
		ConvertUnknownFormat:     -82,
		ConvertTimeout:           -83,
		ConvertReadFile:          -84,
		ConvertCONVERT_CORRUPTED: -86,
		ConvertLIBREOFFICE:       -87,
		ConvertPARAMS:            -88,
		ConvertNEED_PARAMS:       -89,
		ConvertDRM:               -90,
		ConvertPASSWORD:          -91,
		ConvertICU:               -92,
		ConvertLIMITS:            -93,
		ConvertDeadLetter:        -99,

		Upload:              -100,
		UploadContentLength: -101,
		UploadExtension:     -102,
		UploadCountFiles:    -103,
		UploadURL:           -104,

		VKey:                -120,
		VKeyEncrypt:         -121,
		VKeyKeyExpire:       -122,
		VKeyUserCountExceed: -123
	};

	var c_oAscImageUploadProp = {//Не все браузеры позволяют получить информацию о файле до загрузки(например ie9), меняя параметры здесь надо поменять аналогичные параметры в web.common
		MaxFileSize:      25000000, //25 mb
		SupportedFormats: ["jpg", "jpeg", "jpe", "png", "gif", "bmp"]
	};

	/**
	 *
	 * @param sName
	 * @returns {*}
	 * @constructor
	 */
	function GetFileExtension(sName)
	{
		var nIndex = sName ? sName.lastIndexOf(".") : -1;
		if (-1 != nIndex)
			return sName.substring(nIndex + 1).toLowerCase();
		return null;
	}
	function GetFileName(sName)
	{
		var nIndex = sName ? sName.lastIndexOf(".") : -1;
		if (-1 != nIndex)
			return sName.substring(0, nIndex);
		return null;
	}

	function changeFileExtention(sName, sNewExt, opt_lengthLimit)
	{
		var sOldExt = GetFileExtension(sName);
		var nIndexEnd = sOldExt ? sName.length - sOldExt.length - 1 : sName.length;
		if (opt_lengthLimit && nIndexEnd + sNewExt.length + 1 > opt_lengthLimit)
		{
			nIndexEnd = opt_lengthLimit - sNewExt.length - 1;
		}
		if (nIndexEnd < sName.length)
		{
			return sName.substring(0, nIndexEnd) + '.' + sNewExt;
		}
		else
		{
			return sName + '.' + sNewExt;
		}
	}

	function getExtentionByFormat(format)
	{
		switch (format)
		{
			case c_oAscFileType.PDF:
			case c_oAscFileType.PDFA:
				return 'pdf';
				break;
			case c_oAscFileType.HTML:
				return 'html';
				break;
			// Word
			case c_oAscFileType.DOCX:
				return 'docx';
				break;
			case c_oAscFileType.DOC:
				return 'doc';
				break;
			case c_oAscFileType.ODT:
				return 'odt';
				break;
			case c_oAscFileType.RTF:
				return 'rtf';
				break;
			case c_oAscFileType.TXT:
				return 'txt';
				break;
			case c_oAscFileType.MHT:
				return 'mht';
				break;
			case c_oAscFileType.EPUB:
				return 'epub';
				break;
			case c_oAscFileType.FB2:
				return 'fb2';
				break;
			case c_oAscFileType.MOBI:
				return 'mobi';
				break;
			case c_oAscFileType.DOCY:
				return 'doct';
				break;
			case c_oAscFileType.CANVAS_WORD:
				return 'bin';
				break;
			case c_oAscFileType.JSON:
				return 'json';
				break;
			// Excel
			case c_oAscFileType.XLSX:
				return 'xlsx';
				break;
			case c_oAscFileType.XLS:
				return 'xls';
				break;
			case c_oAscFileType.ODS:
				return 'ods';
				break;
			case c_oAscFileType.CSV:
				return 'csv';
				break;
			case c_oAscFileType.XLSY:
				return 'xlst';
				break;
			// PowerPoint
			case c_oAscFileType.PPTX:
				return 'pptx';
				break;
			case c_oAscFileType.PPT:
				return 'ppt';
				break;
			case c_oAscFileType.ODP:
				return 'odp';
				break;
		}
		return '';
	}

	function InitOnMessage(callback)
	{
		if (window.addEventListener)
		{
			window.addEventListener("message", function (event)
			{
				if (null != event && null != event.data)
				{
					try
					{
						var data = JSON.parse(event.data);
						if (null != data && null != data["type"] && PostMessageType.UploadImage == data["type"])
						{
							if (c_oAscServerError.NoError == data["error"])
							{
								var urls = data["urls"];
								if (urls)
								{
									g_oDocumentUrls.addUrls(urls);
									var firstUrl;
									for (var i in urls)
									{
										if (urls.hasOwnProperty(i))
										{
											firstUrl = urls[i];
											break;
										}
									}
									callback(Asc.c_oAscError.ID.No, firstUrl);
								}

							}
							else
								callback(mapAscServerErrorToAscError(data["error"]));
						}
						else if (data.type === "onExternalPluginMessage")
						{
							if (window.g_asc_plugins)
								window.g_asc_plugins.sendToAllPlugins(event.data);
						}
					} catch (err)
					{
					}
				}
			}, false);
		}
	}

	function ShowImageFileDialog(documentId, documentUserId, jwt, callback, callbackOld)
	{
        if (AscCommon.EncryptionWorker && AscCommon.EncryptionWorker.isCryptoImages())
		{
			AscCommon.EncryptionWorker.addCryproImagesFromDialog(callback);
			return;
		}

		var fileName;
		if ("undefined" != typeof(FileReader))
		{
			fileName = GetUploadInput(function (e)
			{
				if (e && e.target && e.target.files)
				{
					var nError = ValidateUploadImage(e.target.files);
					callback(mapAscServerErrorToAscError(nError), e.target.files);
				}
				else
				{
					callback(Asc.c_oAscError.ID.Unknown);
				}
			});
		}
		else
		{
			var frameWindow = GetUploadIFrame();
			var url = sUploadServiceLocalUrlOld + '/' + documentId + '/' + documentUserId + '/' + g_oDocumentUrls.getMaxIndex();
			if (jwt)
			{
				url += '?token=' + encodeURIComponent(jwt);
			}
			var content = '<html><head></head><body><form action="' + url + '" method="POST" enctype="multipart/form-data"><input id="apiiuFile" name="apiiuFile" type="file" accept="image/*" size="1"><input id="apiiuSubmit" name="apiiuSubmit" type="submit" style="display:none;"></form></body></html>';
			frameWindow.document.open();
			frameWindow.document.write(content);
			frameWindow.document.close();

			fileName = frameWindow.document.getElementById("apiiuFile");
			var fileSubmit = frameWindow.document.getElementById("apiiuSubmit");

			fileName.onchange = function (e)
			{
				if (e && e.target && e.target.files)
				{
					var nError = ValidateUploadImage(e.target.files);
					if (c_oAscServerError.NoError != nError)
					{
						callbackOld(mapAscServerErrorToAscError(nError));
						return;
					}
				}
				callbackOld(Asc.c_oAscError.ID.No);
				fileSubmit.click();
			};
		}

		//todo пересмотреть opera
		if (AscBrowser.isOpera)
			setTimeout(function ()
			{
				fileName.click();
			}, 0);
		else
			fileName.click();
	}

	function InitDragAndDrop(oHtmlElement, callback)
	{
		if ("undefined" != typeof(FileReader) && null != oHtmlElement)
		{
			oHtmlElement["ondragover"] = function (e)
			{
                e.preventDefault();
				e.dataTransfer.dropEffect = CanDropFiles(e) ? 'copy' : 'none';
				if (e.dataTransfer.dropEffect == "copy")
				{
                    var editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
					editor.beginInlineDropTarget(e);
                }
				return false;
			};
			oHtmlElement["ondrop"] = function (e)
			{
				e.preventDefault();
				var files = e.dataTransfer.files;
				var nError = ValidateUploadImage(files);

                var editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
                editor.endInlineDropTarget(e);

				if (nError == c_oAscServerError.UploadCountFiles)
				{
					try
					{
                        // test html
                        var htmlValue = e.dataTransfer.getData("text/html");
                        if (htmlValue && !AscCommon.AscBrowser.isIE)
                        {
                            // text html!
                            var index = htmlValue.indexOf("StartHTML");
                            var indexHtml = htmlValue.indexOf("<html");
                            if (-1 == indexHtml)
                                indexHtml = htmlValue.indexOf("<HTML");
                            if (index > 0 && indexHtml > 0 && index < indexHtml)
                                htmlValue = htmlValue.substr(indexHtml);

                            editor["pluginMethod_PasteHtml"](htmlValue);
                            return;
                        }
                    }
                    catch(err)
					{
					}

					try
					{
                        var textValue = e.dataTransfer.getData("text/plain");
                        if (textValue)
                        {
                            editor["pluginMethod_PasteText"](textValue);
                            return;
                        }
                    }
                    catch(err)
					{
					}

                    try
                    {
                        var textValue = e.dataTransfer.getData("Text");
                        if (textValue)
                        {
                            editor["pluginMethod_PasteText"](textValue);
                            return;
                        }
                    }
                    catch(err)
                    {
                    }
				}

				callback(mapAscServerErrorToAscError(nError), files);
			};
		}
	}

	function UploadImageFiles(files, documentId, documentUserId, jwt, callback)
	{
		if (files.length > 0)
		{
			var url = sUploadServiceLocalUrl + '/' + documentId + '/' + documentUserId + '/' + g_oDocumentUrls.getMaxIndex();
			if (jwt)
			{
				url += '?token=' + encodeURIComponent(jwt);
			}

			var aFiles = [];
			for(var i = files.length - 1;  i > - 1; --i){
                aFiles.push(files[i]);
			}
            var file = aFiles.pop();
            var aResultUrls = [];

            var fOnReadyChnageState = function(){
                if (4 == this.readyState){
                    if ((this.status == 200 || this.status == 1223)){
                        var urls = JSON.parse(this.responseText);
                        g_oDocumentUrls.addUrls(urls);
                        for (var i in urls)
                        {
                            if (urls.hasOwnProperty(i))
                            {
                                aResultUrls.push(urls[i]);
                                break;
                            }
                        }
                        if(aFiles.length === 0){
                            callback(Asc.c_oAscError.ID.No, aResultUrls);
                        }
                        else{
                            file = aFiles.pop();
                            var xhr = new XMLHttpRequest();

                            url = sUploadServiceLocalUrl + '/' + documentId + '/' + documentUserId + '/' + g_oDocumentUrls.getMaxIndex();
                            if (jwt)
                            {
                                url += '?token=' + encodeURIComponent(jwt);
                            }

                            xhr.open('POST', url, true);
                            xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream');
                            xhr.onreadystatechange = fOnReadyChnageState;
                            xhr.send(file);
                        }
                    }
                    else
                        callback(Asc.c_oAscError.ID.UplImageFileCount);
                }
            };

			var xhr = new XMLHttpRequest();
			xhr.open('POST', url, true);
			xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream');
			xhr.onreadystatechange = fOnReadyChnageState;
			xhr.send(file);
		}
		else
		{
			callback(Asc.c_oAscError.ID.UplImageFileCount);
		}
	}

    function UploadImageUrls(files, documentId, documentUserId, jwt, callback)
    {
        if (files.length > 0)
        {
            var url = sUploadServiceLocalUrl + '/' + documentId + '/' + documentUserId + '/' + g_oDocumentUrls.getMaxIndex();
            if (jwt)
            {
                url += '?token=' + encodeURIComponent(jwt);
            }

            var aFiles = [];
            for(var i = files.length - 1;  i > - 1; --i){
                aFiles.push(files[i]);
            }
            var file = aFiles.pop();
            var aResultUrls = [];

            var fOnReadyChnageState = function()
			{
                if (4 == this.readyState)
                {
                    if ((this.status == 200 || this.status == 1223))
                    {
                        var urls = JSON.parse(this.responseText);
                        g_oDocumentUrls.addUrls(urls);
                        for (var i in urls)
                        {
                            if (urls.hasOwnProperty(i))
                            {
                                aResultUrls.push({ path: i, url: urls[i] });
                                break;
                            }
                        }
                        if (aFiles.length === 0)
                        {
                            callback(aResultUrls);
                        }
                        else
						{
                            file = aFiles.pop();
                            var xhr = new XMLHttpRequest();

                            url = sUploadServiceLocalUrl + '/' + documentId + '/' + documentUserId + '/' + g_oDocumentUrls.getMaxIndex();
                            if (jwt)
                            {
                                url += '?token=' + encodeURIComponent(jwt);
                            }

                            xhr.open('POST', url, true);
                            xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream');
                            xhr.onreadystatechange = fOnReadyChnageState;
                            xhr.send(file);
                        }
                    }
                    else
                        callback([]);
                }
            };

            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream');
            xhr.onreadystatechange = fOnReadyChnageState;
            xhr.send(file);
        }
        else
        {
            callback(Asc.c_oAscError.ID.UplImageFileCount);
        }
    }

	function ValidateUploadImage(files)
	{
		var nRes = c_oAscServerError.NoError;
		if (files.length > 0)
		{
			for (var i = 0, length = files.length; i < length; i++)
			{
				var file = files[i];
				//проверяем расширение файла
				var sName = file.fileName || file.name;
				if (sName)
				{
					var bSupported = false;
					var ext = GetFileExtension(sName);
					if (null !== ext)
					{
						for (var j = 0, length2 = c_oAscImageUploadProp.SupportedFormats.length; j < length2; j++)
						{
							if (c_oAscImageUploadProp.SupportedFormats[j] == ext)
							{
								bSupported = true;
								break;
							}
						}
					}
					if (false == bSupported)
						nRes = c_oAscServerError.UploadExtension;
				}
				if (Asc.c_oAscError.ID.No == nRes)
				{
					var nSize = file.fileSize || file.size;
					if (nSize && c_oAscImageUploadProp.MaxFileSize < nSize)
						nRes = c_oAscServerError.UploadContentLength;
				}
				if (c_oAscServerError.NoError != nRes)
					break;
			}
		}
		else
			nRes = c_oAscServerError.UploadCountFiles;
		return nRes;
	}

	function CanDropFiles(event)
	{
        var editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
        if (!editor.isEnabledDropTarget())
        	return false;

		var bRes = false;
		if (event.dataTransfer.types)
		{
			for (var i = 0, length = event.dataTransfer.types.length; i < length; ++i)
			{
				var type = event.dataTransfer.types[i].toLowerCase();
				if (type == "files")
				{
					if (event.dataTransfer.items)
					{
						for (var j = 0, length2 = event.dataTransfer.items.length; j < length2; j++)
						{
							var item = event.dataTransfer.items[j];
							if (item.type && item.kind && "file" == item.kind.toLowerCase())
							{
								bRes = false;
								for (var k = 0,
										 length3 = c_oAscImageUploadProp.SupportedFormats.length; k < length3; k++)
								{
									if (-1 != item.type.indexOf(c_oAscImageUploadProp.SupportedFormats[k]))
									{
										bRes = true;
										break;
									}
								}
								if (false == bRes)
									break;
							}
						}
					}
					else
						bRes = true;
					break;
				}
				else if (type == "text" || type == "text/plain" || type == "text/html")
				{
                    bRes = true;
                    break;
				}
			}
		}
		return bRes;
	}

	function GetUploadIFrame()
	{
		var sIFrameName = "apiImageUpload";
		var oImageUploader = document.getElementById(sIFrameName);
		if (!oImageUploader)
		{
			var frame = document.createElement("iframe");
			frame.name = sIFrameName;
			frame.id = sIFrameName;
			frame.setAttribute("style", "position:absolute;left:-2px;top:-2px;width:1px;height:1px;z-index:-1000;");
			document.body.appendChild(frame);
		}
		return window.frames[sIFrameName];
	}

	function GetUploadInput(onchange)
	{
		var inputName = 'apiiuFile';
		var input = document.getElementById(inputName);
		//удаляем чтобы очистить input от предыдущего ввода
		if (input)
		{
			document.body.removeChild(input);
		}
		input = document.createElement("input");
		input.setAttribute('id', inputName);
		input.setAttribute('name', inputName);
		input.setAttribute('type', 'file');
		input.setAttribute('accept', 'image/*');
		input.setAttribute('style', 'position:absolute;left:-2px;top:-2px;width:1px;height:1px;z-index:-1000;cursor:pointer;');
		input.onchange = onchange;
		document.body.appendChild(input);
		return input;
	}

	var FormulaSeparators = {
		arrayRowSeparatorDef:         ';',
		arrayColSeparatorDef:         ',',
		digitSeparatorDef:            '.',
		functionArgumentSeparatorDef: ',',
		arrayRowSeparator:            ';',
		arrayColSeparator:            ',',
		digitSeparator:               '.',
		functionArgumentSeparator:    ','
	};

	var g_oCodeSpace = 32; // Code of space
	var g_oCodeLineFeed = 10; // Code of line feed
	var g_arrCodeOperators = [37, 38, 42, 43, 45, 47, 58, 94]; // Code of operators [%, &, *, +, -, /, :, ^]
	var g_oStartCodeOperatorsCompare = 60; // Start code of operators <=>
	var g_oEndCodeOperatorsCompare = 62; // End code of operators <=>
	var g_oCodeLeftParentheses = 40; // Code of (
	var g_oCodeRightParentheses = 41; // Code of )
	var g_oCodeLeftBrace = 123; // Code of {
	var g_oCodeRightBrace = 125; // Code of }

	/*Functions that checks of an element in formula*/
	var str_namedRanges       = "A-Za-z\u005F\u0080-\u0081\u0083\u0085-\u0087\u0089-\u008A\u008C-\u0091\u0093-\u0094\u0096-\u0097\u0099-\u009A\u009C-\u009F\u00A1-\u00A5\u00A7-\u00A8\u00AA\u00AD\u00AF-\u00BA\u00BC-\u02B8\u02BB-\u02C1\u02C7\u02C9-\u02CB\u02CD\u02D0-\u02D1\u02D8-\u02DB\u02DD\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0621-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4-\u07F5\u07FA\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0972\u097B-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D3D\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E3A\u0E40-\u0E4E\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDD\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8B\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10D0-\u10FA\u10FC\u1100-\u1159\u115F-\u11A2\u11A8-\u11F9\u1200-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u1676\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19A9\u19C1-\u19C7\u1A00-\u1A16\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200e\u2010\u2013-\u2016\u2018\u201C-\u201D\u2020-\u2021\u2025-\u2027\u2030\u2032-\u2033\u2035\u203B\u2071\u2074\u207F\u2081-\u2084\u2090-\u2094\u2102-\u2103\u2105\u2107\u2109-\u2113\u2115-\u2116\u2119-\u211D\u2121-\u2122\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2153-\u2154\u215B-\u215E\u2160-\u2188\u2190-\u2199\u21D2\u21D4\u2200\u2202-\u2203\u2207-\u2208\u220B\u220F\u2211\u2215\u221A\u221D-\u2220\u2223\u2225\u2227-\u222C\u222E\u2234-\u2237\u223C-\u223D\u2248\u224C\u2252\u2260-\u2261\u2264-\u2267\u226A-\u226B\u226E-\u226F\u2282-\u2283\u2286-\u2287\u2295\u2299\u22A5\u22BF\u2312\u2460-\u24B5\u24D0-\u24E9\u2500-\u254B\u2550-\u2574\u2581-\u258F\u2592-\u2595\u25A0-\u25A1\u25A3-\u25A9\u25B2-\u25B3\u25B6-\u25B7\u25BC-\u25BD\u25C0-\u25C1\u25C6-\u25C8\u25CB\u25CE-\u25D1\u25E2-\u25E5\u25EF\u2605-\u2606\u2609\u260E-\u260F\u261C\u261E\u2640\u2642\u2660-\u2661\u2663-\u2665\u2667-\u266A\u266C-\u266D\u266F\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C6F\u2C71-\u2C7D\u2C80-\u2CE4\u2D00-\u2D25\u2D30-\u2D65\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3000-\u3003\u3005-\u3017\u301D-\u301F\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31B7\u31F0-\u321C\u3220-\u3229\u3231-\u3232\u3239\u3260-\u327B\u327F\u32A3-\u32A8\u3303\u330D\u3314\u3318\u3322-\u3323\u3326-\u3327\u332B\u3336\u333B\u3349-\u334A\u334D\u3351\u3357\u337B-\u337E\u3380-\u3384\u3388-\u33CA\u33CD-\u33D3\u33D5-\u33D6\u33D8\u33DB-\u33DD\u3400-\u4DB5\u4E00-\u9FC3\uA000-\uA48C\uA500-\uA60C\uA610-\uA61F\uA62A-\uA62B\uA640-\uA65F\uA662-\uA66E\uA680-\uA697\uA722-\uA787\uA78B-\uA78C\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA90A-\uA925\uA930-\uA946\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAC00-\uD7A3\uE000-\uF848\uF900-\uFA2D\uFA30-\uFA6A\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE30-\uFE31\uFE33-\uFE44\uFE49-\uFE52\uFE54-\uFE57\uFE59-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFF01-\uFF5E\uFF61-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6",
		str_namedSheetsRange  = "\u0001-\u0026\u0028-\u0029\u002B-\u002D\u003B-\u003E\u0040\u005E\u0060\u007B-\u007F\u0082\u0084\u008B\u0092\u0095\u0098\u009B\u00A0\u00A6\u00A9\u00AB-\u00AC\u00AE\u00BB\u0378-\u0379\u037E-\u0383\u0387\u038B\u038D\u03A2\u0524-\u0530\u0557-\u0558\u055A-\u0560\u0588-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EF\u05F3-\u05FF\u0604-\u0605\u0609-\u060A\u060C-\u060D\u061B-\u061E\u0620\u065F\u066A-\u066D\u06D4\u0700-\u070E\u074B-\u074C\u07B2-\u07BF\u07F7-\u07F9\u07FB-\u0900\u093A-\u093B\u094E-\u094F\u0955-\u0957\u0964-\u0965\u0970\u0973-\u097A\u0980\u0984\u098D-\u098E\u0991-\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BB\u09C5-\u09C6\u09C9-\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4-\u09E5\u09FB-\u0A00\u0A04\u0A0B-\u0A0E\u0A11-\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A3B\u0A3D\u0A43-\u0A46\u0A49-\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABB\u0AC6\u0ACA\u0ACE-\u0ACF\u0AD1-\u0ADF\u0AE4-\u0AE5\u0AF0\u0AF2-\u0B00\u0B04\u0B0D-\u0B0E\u0B11-\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3B\u0B45-\u0B46\u0B49-\u0B4A\u0B4E-\u0B55\u0B58-\u0B5B\u0B5E\u0B64-\u0B65\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE-\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BFB-\u0C00\u0C04\u0C0D\u0C11\u0C29\u0C34\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5A-\u0C5F\u0C64-\u0C65\u0C70-\u0C77\u0C80-\u0C81\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4-\u0CE5\u0CF0\u0CF3-\u0D01\u0D04\u0D0D\u0D11\u0D29\u0D3A-\u0D3C\u0D45\u0D49\u0D4E-\u0D56\u0D58-\u0D5F\u0D64-\u0D65\u0D76-\u0D78\u0D80-\u0D81\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE-\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3E\u0E4F\u0E5A-\u0E80\u0E83\u0E85-\u0E86\u0E89\u0E8B-\u0E8C\u0E8E-\u0E93\u0E98\u0EA0\u0EA4\u0EA6\u0EA8-\u0EA9\u0EAC\u0EBA\u0EBE-\u0EBF\u0EC5\u0EC7\u0ECE-\u0ECF\u0EDA-\u0EDB\u0EDE-\u0EFF\u0F04-\u0F12\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F8C-\u0F8F\u0F98\u0FBD\u0FCD\u0FD0-\u0FFF\u104A-\u104F\u109A-\u109D\u10C6-\u10CF\u10FB\u10FD-\u10FF\u115A-\u115E\u11A3-\u11A7\u11FA-\u11FF\u1249\u124E-\u124F\u1257\u1259\u125E-\u125F\u1289\u128E-\u128F\u12B1\u12B6-\u12B7\u12BF\u12C1\u12C6-\u12C7\u12D7\u1311\u1316-\u1317\u135B-\u135E\u1361-\u1368\u137D-\u137F\u139A-\u139F\u13F5-\u1400\u166D-\u166E\u1677-\u167F\u169B-\u169F\u16EB-\u16ED\u16F1-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DA\u17DE-\u17DF\u17EA-\u17EF\u17FA-\u180A\u180F\u181A-\u181F\u1878-\u187F\u18AB-\u18FF\u191D-\u191F\u192C-\u192F\u193C-\u193F\u1941-\u1945\u196E-\u196F\u1975-\u197F\u19AA-\u19AF\u19CA-\u19CF\u19DA-\u19DF\u1A1C-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BAB-\u1BAD\u1BBA-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E-\u1CFF\u1DE7-\u1DFD\u1F16-\u1F17\u1F1E-\u1F1F\u1F46-\u1F47\u1F4E-\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E-\u1F7F\u1FB5\u1FC5\u1FD4-\u1FD5\u1FDC\u1FF0-\u1FF1\u1FF5\u1FFF\u200e\u2011-\u2012\u2017\u2019-\u201B\u201E-\u201F\u2022-\u2024\u2031\u2034\u2036-\u203A\u203C-\u2043\u2045-\u2051\u2053-\u205E\u2065-\u2069\u2072-\u2073\u207D-\u207E\u208D-\u208F\u2095-\u209F\u20B6-\u20CF\u20F1-\u20FF\u2150-\u2152\u2189-\u218F\u2329-\u232A\u23E8-\u23FF\u2427-\u243F\u244B-\u245F\u269E-\u269F\u26BD-\u26BF\u26C4-\u2700\u2705\u270A-\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u275F-\u2760\u2768-\u2775\u2795-\u2797\u27B0\u27BF\u27C5-\u27C6\u27CB\u27CD-\u27CF\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC-\u29FD\u2B4D-\u2B4F\u2B55-\u2BFF\u2C2F\u2C5F\u2C70\u2C7E-\u2C7F\u2CEB-\u2CFC\u2CFE-\u2CFF\u2D26-\u2D2F\u2D66-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u2FFF\u3018-\u301C\u3030\u303D\u3040\u3097-\u3098\u30A0\u3100-\u3104\u312E-\u3130\u318F\u31B8-\u31BF\u31E4-\u31EF\u321F\u3244-\u324F\u32FF\u4DB6-\u4DBF\u9FC4-\u9FFF\uA48D-\uA48F\uA4C7-\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA660-\uA661\uA673-\uA67B\uA67E\uA698-\uA6FF\uA78D-\uA7FA\uA82C-\uA83F\uA874-\uA87F\uA8C5-\uA8CF\uA8DA-\uA8FF\uA92F\uA954-\uA9FF\uAA37-\uAA3F\uAA4E-\uAA4F\uAA5A-\uABFF\uD7A4-\uD7FF\uFA2E-\uFA2F\uFA6B-\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90-\uFD91\uFDC8-\uFDEF\uFDFE-\uFDFF\uFE10-\uFE1F\uFE27-\uFE2F\uFE32\uFE45-\uFE48\uFE53\uFE58\uFE67\uFE6C-\uFE6F\uFE75\uFEFD-\uFEFE\uFF00\uFF5F-\uFF60\uFFBF-\uFFC1\uFFC8-\uFFC9\uFFD0-\uFFD1\uFFD8-\uFFD9\uFFDD-\uFFDF\uFFE7\uFFEF-\uFFF8\uFFFE-\uFFFF",
		rx_operators          = /^ *[-+*\/^&%<=>:] */,
		rg                    = new XRegExp("^((?:_xlfn.)?[\\p{L}\\d.]+ *)[-+*/^&%<=>:;\\(\\)]"),
		rgRange               = /^(\$?[A-Za-z]+\$?\d+:\$?[A-Za-z]+\$?\d+)(?:[-+*\/^&%<=>: ;),]|$)/,
		rgRangeR1C1           = /^(([Rr]{1}(\[)?(-?\d*)(\])?)([Cc]{1}(\[)?(-?\d*)(\])?):([Rr]{1}(\[)?(-?\d*)(\])?)([Cc]{1}(\[)?(-?\d*)(\])?))([-+*\/^&%<=>: ;),]|$)/,
		rgCols                = /^(\$?[A-Za-z]+:\$?[A-Za-z]+)(?:[-+*\/^&%<=>: ;),]|$)/,
		rgColsR1C1            = /^(([Cc]{1}(\[)?(-?\d*)(\])?(:)?)([Cc]?(\[)?(-?\d*)(\])?))([-+*\/^&%<=>: ;),]|$)/,
		rgRows                = /^(\$?\d+:\$?\d+)(?:[-+*\/^&%<=>: ;),]|$)/,
		rgRowsR1C1            = /^(([Rr]{1}(\[)?(-?\d*)(\])?(:)?)([Rr]?(\[)?(-?\d*)(\])?))([-+*\/^&%<=>: ;),]|$)/,
		rx_ref                = /^ *(\$?[A-Za-z]{1,3}\$?(\d{1,7}))([-+*\/^&%<=>: ;),]|$)/,
		rx_refAll             = /^(\$?[A-Za-z]+\$?(\d+))([-+*\/^&%<=>: ;),]|$)/,
		rx_refR1C1             = /^(([Rr]{1}(\[)?(-?\d*)(\])?)([Cc]{1}(\[)?(-?\d*)(\])?))([-+*\/^&%<=>: ;),]|$)/,
		rx_ref3D_non_quoted   = new XRegExp("^(?<name_from>[" + str_namedRanges + "][" + str_namedRanges + "\\d.]*)(:(?<name_to>[" + str_namedRanges + "][" + str_namedRanges + "\\d.]*))?!", "i"),
		rx_ref3D_quoted       = new XRegExp("^'(?<name_from>(?:''|[^\\[\\]'\\/*?:])*)(?::(?<name_to>(?:''|[^\\[\\]'\\/*?:])*))?'!"),
		rx_ref3D              = new XRegExp("^(?<name_from>[^:]+)(:(?<name_to>[^:]+))?!"),
		rx_number             = /^ *[+-]?\d*(\d|\.)\d*([eE][+-]?\d+)?/,
		rx_RightParentheses   = /^ *\)/,
		rx_Comma              = /^ *[,;] */,
		rx_arraySeparators    = /^ *[,;] */,

		rx_error              = build_rx_error(null),
		rx_error_local        = build_rx_error(null),

		rx_bool               = build_rx_bool(cBoolOrigin),
		rx_bool_local         = rx_bool,
		rx_string             = /^\"((\"\"|[^\"])*)\"/,
		rx_test_ws_name       = new test_ws_name2(),
		rx_space_g            = /\s/g,
		rx_space              = /\s/,
		rx_intersect          = /^ +/,
		rg_str_allLang        = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0345\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05B0-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0657\u0659-\u065F\u066E-\u06D3\u06D5-\u06DC\u06E1-\u06E8\u06ED-\u06EF\u06FA-\u06FC\u06FF\u0710-\u073F\u074D-\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0817\u081A-\u082C\u0840-\u0858\u08A0\u08A2-\u08AC\u08E4-\u08E9\u08F0-\u08FE\u0900-\u093B\u093D-\u094C\u094E-\u0950\u0955-\u0963\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C4\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09F0\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A42\u0A47\u0A48\u0A4B\u0A4C\u0A51\u0A59-\u0A5C\u0A5E\u0A70-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC5\u0AC7-\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0-\u0AE3\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D-\u0B44\u0B47\u0B48\u0B4B\u0B4C\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4C\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCC\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D57\u0D60-\u0D63\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E46\u0E4D\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0ECD\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F71-\u0F81\u0F88-\u0F97\u0F99-\u0FBC\u1000-\u1036\u1038\u103B-\u103F\u1050-\u1062\u1065-\u1068\u106E-\u1086\u108E\u109C\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1713\u1720-\u1733\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17B3\u17B6-\u17C8\u17D7\u17DC\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u1938\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A1B\u1A20-\u1A5E\u1A61-\u1A74\u1AA7\u1B00-\u1B33\u1B35-\u1B43\u1B45-\u1B4B\u1B80-\u1BA9\u1BAC-\u1BAF\u1BBA-\u1BE5\u1BE7-\u1BF1\u1C00-\u1C35\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u24B6-\u24E9\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA674-\uA67B\uA67F-\uA697\uA69F-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA827\uA840-\uA873\uA880-\uA8C3\uA8F2-\uA8F7\uA8FB\uA90A-\uA92A\uA930-\uA952\uA960-\uA97C\uA980-\uA9B2\uA9B4-\uA9BF\uA9CF\uAA00-\uAA36\uAA40-\uAA4D\uAA60-\uAA76\uAA7A\uAA80-\uAABE\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,
		rx_name               = new XRegExp("^(?<name>" + "[" + str_namedRanges + "][" + str_namedRanges + "\\d.]*)([-+*\\/^&%<=>: ;/\n/),]|$)"),
		rx_defName            = new test_defName(),
		rx_arraySeparatorsDef = /^ *[,;] */,
		rx_numberDef          = /^ *[+-]?\d*(\d|\.)\d*([eE][+-]?\d+)?/,
		rx_CommaDef           = /^ *[,;] */,

		rx_ControlSymbols     = /^ *[\u0000-\u001F\u007F-\u009F] */,

		emailRe               = /^(mailto:)?([a-z0-9'\._-]+@[a-z0-9\.-]+\.[a-z0-9]{2,4})([a-яё0-9\._%+-=\? :&]*)/i,
		ipRe                  = /^(((https?)|(ftps?)):\/\/)?([\-\wа-яё]*:?[\-\wа-яё]*@)?(((1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9])\.){3}(1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9][0-9]|[0-9]))(:\d+)?(\/[%\-\wа-яё]*(\.[\wа-яё]{2,})?(([\wа-яё\-\.\?\\\/+@&#;:`~=%!,\(\)]*)(\.[\wа-яё]{2,})?)*)*\/?/i,
		hostnameRe            = /^(((https?)|(ftps?)):\/\/)?([\-\wа-яё]*:?[\-\wа-яё]*@)?(([\-\wа-яё]+\.)+[\wа-яё\-]{2,}(:\d+)?(\/[%\-\wа-яё]*(\.[\wа-яё]{2,})?(([\wа-яё\-\.\?\\\/+@&#;:`'~=%!,\(\)]*)(\.[\wа-яё]{2,})?)*)*\/?)/i,
		localRe               = /^(((https?)|(ftps?)):\/\/)([\-\wа-яё]*:?[\-\wа-яё]*@)?(([\-\wа-яё]+)(:\d+)?(\/[%\-\wа-яё]*(\.[\wа-яё]{2,})?(([\wа-яё\-\.\?\\\/+@&#;:`'~=%!,\(\)]*)(\.[\wа-яё]{2,})?)*)*\/?)/i,

		rx_table              = build_rx_table(null),
		rx_table_local        = build_rx_table(null);

	function getUrlType(url)
	{
		var checkvalue = url.replace(new RegExp(' ', 'g'), '%20');
		var isEmail;
		var isvalid = checkvalue.strongMatch(hostnameRe);
		!isvalid && (isvalid = checkvalue.strongMatch(ipRe));
		!isvalid && (isvalid = checkvalue.strongMatch(localRe));
		isEmail = checkvalue.strongMatch(emailRe);
		!isvalid && (isvalid = isEmail);

		return isvalid ? (isEmail ? AscCommon.c_oAscUrlType.Email : AscCommon.c_oAscUrlType.Http) : AscCommon.c_oAscUrlType.Invalid;
	}

	function prepareUrl(url, type)
	{
		if (!/(((^https?)|(^ftp)):\/\/)|(^mailto:)/i.test(url))
		{
			url = ( (AscCommon.c_oAscUrlType.Email == type) ? 'mailto:' : 'http://' ) + url;
		}

		return url.replace(new RegExp("%20", 'g'), " ");
	}

	/**
	 * вспомогательный объект для парсинга формул и проверки строки по регуляркам указанным выше.
	 * @constructor
	 */
	function parserHelper()
	{
		this.operand_str = null;
		this.pCurrPos = null;
	}

	parserHelper.prototype._reset = function ()
	{
		this.operand_str = null;
		this.pCurrPos = null;
	};
	parserHelper.prototype.isControlSymbols = function (formula, start_pos, digitDelim)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(rx_ControlSymbols);
		if (match != null)
		{
			this.operand_str = match[0];
			this.pCurrPos += match[0].length;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isOperator = function (formula, start_pos)
	{
		// ToDo нужно ли это?
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var code, find = false, length = formula.length;
		while (start_pos !== length)
		{
			code = formula.charCodeAt(start_pos);
			if (-1 !== g_arrCodeOperators.indexOf(code))
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				find = true;
				break;
			}
			else if (g_oStartCodeOperatorsCompare <= code && code <= g_oEndCodeOperatorsCompare)
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				while (start_pos !== length)
				{
					code = formula.charCodeAt(start_pos);
					if (g_oStartCodeOperatorsCompare > code || code > g_oEndCodeOperatorsCompare)
					{
						break;
					}
					this.operand_str += formula[start_pos];
					++start_pos;
				}
				find = true;
				break;
			}
			else if (code === g_oCodeSpace || code === g_oCodeLineFeed)
			{
				++start_pos;
			}
			else
			{
				break;
			}
		}
		if (find)
		{
			while (start_pos !== length)
			{
				code = formula.charCodeAt(start_pos);
				if (code !== g_oCodeSpace &&  code !== g_oCodeLineFeed)
				{
					break;
				}
				++start_pos;
			}
			this.pCurrPos = start_pos;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isFunc = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var frml = formula.substring(start_pos);
		var match = (frml).match(rg);

		if (match != null)
		{
			if (match.length == 2)
			{
				this.pCurrPos += match[1].length;
				this.operand_str = match[1];
				return true;
			}
		}
		return false;
	};
	parserHelper.prototype.convertFromR1C1 = function (r, c, isAbsRow, isAbsCol)
	{
		var activeCell = AscCommonExcel.g_ActiveCell;
		var colStr, rowStr, res = "";
		if(r !== null && c !== null) {
			if(isNaN(r)) {
				r = 0;
				isAbsRow = false;
			}
			if(isNaN(c)) {
				c = 0;
				isAbsCol = false;
			}

			colStr = g_oCellAddressUtils.colnumToColstrFromWsView(!isAbsCol && activeCell ? activeCell.c1 + 1 + c : c);
			rowStr = !isAbsRow && activeCell ? activeCell.r1 + 1 + r : r;
			if(isAbsCol) {
				colStr = "$" + colStr;
			}
			if(isAbsRow) {
				rowStr = "$" + rowStr;
			}
			res = colStr + rowStr;
		} else if(c !== null) {
			if(isNaN(c)) {
				c = 0;
				isAbsCol = false;
			}
			colStr = g_oCellAddressUtils.colnumToColstrFromWsView(!isAbsCol && activeCell ? activeCell.c1 + 1 + c : c);
			if(isAbsCol) {
				colStr = "$" + colStr;
			}
			res = colStr;
		} else if(r !== null) {
			if(isNaN(r)) {
				r = 0;
				isAbsRow = false;
			}
			rowStr = !isAbsRow && activeCell ? activeCell.r1 + 1 + r + "" : r + "";
			if(isAbsRow) {
				rowStr = "$" + rowStr;
			}
			res = rowStr;
		}
		return res;
	};
	parserHelper.prototype.isArea = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var checkAbs = function(val1, val2) {
			var res = null;
			if(val1 === val2 && val1 === undefined) {
				res = true;
			} else if(val1 === "[" && val2 === "]") {
				res = false;
			}
			return res;
		};

		var checkMatchRowCol = function(tempMatch) {
			var res = true;

			if(tempMatch[9] !== "" && tempMatch[9] !== undefined && !(tempMatch[6] === ":" && tempMatch[7] !== "" && tempMatch[7] !== undefined)) {
				res = false;
			} else if(tempMatch[7] !== "" && tempMatch[7] !== undefined && tempMatch[6] !== ":") {
				res = false;
			} else if((tempMatch[7] === "" || tempMatch[7] === undefined) && tempMatch[6] === ":") {
				res = false;
			}

			return res;
		};

		var R1C1Mode = AscCommonExcel.g_R1C1Mode;
		var subSTR = formula.substring(start_pos);

		var match;
		if(!R1C1Mode) {
			match = subSTR.match(rgRange) || subSTR.match(rgCols) || subSTR.match(rgRows);
			if (match != null)
			{
				var m0 = match[1].split(":");
				if (g_oCellAddressUtils.getCellAddress(m0[0]).isValid() && g_oCellAddressUtils.getCellAddress(m0[1]).isValid())
				{
					this.pCurrPos += match[1].length;
					this.operand_str = match[1];
					return true;
				}
			}
		} else {
			var abs1Val, abs2Val, abs3Val, abs4Val, ref1, ref2;
			if((match = subSTR.match(rgRangeR1C1)) !== null) {
				abs1Val = checkAbs(match[3], match[5]);
				abs2Val = checkAbs(match[7], match[9]);
				abs3Val = checkAbs(match[11], match[13]);
				abs4Val = checkAbs(match[15], match[17]);
				if(abs1Val !== null && abs2Val !== null && abs3Val !== null && abs4Val !== null) {
					ref1 = AscCommon.parserHelp.convertFromR1C1(parseInt(match[4]), parseInt(match[8]), abs1Val, abs2Val);
					ref2 = AscCommon.parserHelp.convertFromR1C1(parseInt(match[12]), parseInt(match[16]), abs3Val, abs4Val);
					if (g_oCellAddressUtils.getCellAddress(ref1).isValid() && g_oCellAddressUtils.getCellAddress(ref2).isValid()) {
						this.pCurrPos += match[1].length;
						this.operand_str = match[1];
						this.real_str = ref1 + ":" + ref2;

						return true;
					}
				}
			} else if(null != (match = subSTR.match(rgColsR1C1))) {
				if(checkMatchRowCol(match)) {
					abs1Val = checkAbs(match[3], match[5]);
					abs2Val = checkAbs(match[8], match[10]);
					if(abs1Val !== null && abs2Val !== null) {

						ref1 = AscCommon.parserHelp.convertFromR1C1(null, parseInt(match[4]), null, abs1Val);
						ref2 = "" !== match[7] ? AscCommon.parserHelp.convertFromR1C1(null, parseInt(match[9]), null, abs2Val) : ref1;
						if (g_oCellAddressUtils.getCellAddress(ref1).isValid() && g_oCellAddressUtils.getCellAddress(ref2).isValid()) {
							this.pCurrPos += match[1].length;
							this.operand_str = match[1];
							this.real_str = ref1 + ":" + ref2;

							return true;
						}
					}
				}
			} else if(null != (match = subSTR.match(rgRowsR1C1))) {
				if(checkMatchRowCol(match)) {
					abs1Val = checkAbs(match[3], match[5]);
					abs2Val = checkAbs(match[8], match[10]);
					if(abs1Val !== null && abs2Val !== null) {

						ref1 = AscCommon.parserHelp.convertFromR1C1(parseInt(match[4]), null, abs1Val);
						ref2 = "" !== match[7] ? AscCommon.parserHelp.convertFromR1C1(parseInt(match[9]), null, abs2Val) : ref1;
						if (g_oCellAddressUtils.getCellAddress(ref1).isValid() && g_oCellAddressUtils.getCellAddress(ref2).isValid()) {
							this.pCurrPos += match[1].length;
							this.operand_str = match[1];
							this.real_str = ref1 + ":" + ref2;

							return true;
						}
					}
				}
			}
		}
		return false;
	};
	parserHelper.prototype.isRef = function (formula, start_pos, allRef)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var R1C1Mode = AscCommonExcel.g_R1C1Mode;
		var substr = formula.substring(start_pos), match;
		var m0, m1;
		if(!R1C1Mode) {
			match = substr.match(rx_ref);
			if (match != null)
			{
				m0 = match[0];
				m1 = match[1];
				if (g_oCellAddressUtils.getCellAddress(m1).isValid())
				{
					this.pCurrPos += m0.indexOf(" ") > -1 ? m0.length - 1 : m1.length;
					this.operand_str = m1;
					return true;
				}
				else if (allRef)
				{
					match = substr.match(rx_refAll);
					if ((match != null || match != undefined) && match.length >= 3)
					{
						m1 = match[1];
						this.pCurrPos += m1.length;
						this.operand_str = m1;
						return true;
					}
				}
			}
		} else {
			match = substr.match(rx_refR1C1);

			if (match != null && (match[3] === match[5] || (match[3] === "[" && match[5] === "]")) && (match[7] === match[9] || (match[7] === "[" && match[9] === "]"))) {
				m0 = match[0];
				m1 = match[1];
				var ref = AscCommon.parserHelp.convertFromR1C1(parseInt(match[4]), parseInt(match[8]), !match[3], !match[7]);
				if (g_oCellAddressUtils.getCellAddress(ref).isValid()) {
					this.pCurrPos += m0.indexOf(" ") > -1 ? m0.length - 1 : m1.length;
					this.operand_str = m1;
					this.real_str = ref;

					return true;
				}
			}
		}

		return false;
	};
	parserHelper.prototype.is3DRef = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var subSTR = formula.substring(start_pos),
			match  = XRegExp.exec(subSTR, rx_ref3D_quoted) || XRegExp.exec(subSTR, rx_ref3D_non_quoted);

		if (match != null)
		{
			this.pCurrPos += match[0].length;
			this.operand_str = match[1];
			return [true, match["name_from"] ? match["name_from"].replace(/''/g, "'") : null, match["name_to"] ? match["name_to"].replace(/''/g, "'") : null];
		}
		return [false, null, null];
	};
	parserHelper.prototype.isNextPtg = function (formula, start_pos, digitDelim)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var subSTR = formula.substring(start_pos), match;
		if (subSTR.match(rx_RightParentheses) == null && subSTR.match(digitDelim ? rx_Comma : rx_CommaDef) == null &&
			subSTR.match(rx_operators) == null && (match = subSTR.match(rx_intersect)) != null)
		{
			this.pCurrPos += match[0].length;
			this.operand_str = match[0][0];
			return true;
		}
		return false;
	};
	parserHelper.prototype.isNumber = function (formula, start_pos, digitDelim)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(digitDelim ? rx_number : rx_numberDef);
		if (match != null)
		{
			this.operand_str = match[0].replace(FormulaSeparators.digitSeparator, FormulaSeparators.digitSeparatorDef);
			this.pCurrPos += match[0].length;

			return true;
		}
		return false;
	};
	parserHelper.prototype.isLeftParentheses = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var code, find = false, length = formula.length;
		while (start_pos !== length)
		{
			code = formula.charCodeAt(start_pos);
			if (code === g_oCodeLeftParentheses)
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				find = true;
				break;
			}
			else if (code === g_oCodeSpace)
			{
				++start_pos;
			}
			else
			{
				break;
			}
		}

		if (find)
		{
			while (start_pos !== length)
			{
				code = formula.charCodeAt(start_pos);
				if (code !== g_oCodeSpace)
				{
					break;
				}
				++start_pos;
			}
			this.pCurrPos = start_pos;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isRightParentheses = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var code, find = false, length = formula.length;
		while (start_pos !== length)
		{
			code = formula.charCodeAt(start_pos);
			if (code === g_oCodeRightParentheses)
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				find = true;
				break;
			}
			else if (code === g_oCodeSpace)
			{
				++start_pos;
			}
			else
			{
				break;
			}
		}

		if (find)
		{
			while (start_pos !== length)
			{
				code = formula.charCodeAt(start_pos);
				if (code !== g_oCodeSpace)
				{
					break;
				}
				++start_pos;
			}
			this.pCurrPos = start_pos;
			return true;
		}
	};
	parserHelper.prototype.isComma = function (formula, start_pos, digitDelim)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(digitDelim ? rx_Comma : rx_CommaDef);
		if (match != null)
		{
			this.operand_str = match[0];
			this.pCurrPos += match[0].length;

			return true;
		}
		return false;
	};
	parserHelper.prototype.isArraySeparator = function (formula, start_pos, digitDelim)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(digitDelim ? rx_arraySeparators : rx_arraySeparatorsDef);
		if (match != null)
		{
			this.operand_str = match[0];
			this.pCurrPos += match[0].length;

			return true;
		}
		return false;
	};
	parserHelper.prototype.isError = function (formula, start_pos, local)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(local ? rx_error_local : rx_error);
		if (match != null)
		{
			this.operand_str = match[0];
			this.pCurrPos += match[0].length;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isBoolean = function (formula, start_pos, local)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(local ? rx_bool_local : rx_bool);
		if (match != null)
		{
			this.operand_str = match[1];
			this.pCurrPos += match[1].length;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isString = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var match = (formula.substring(start_pos)).match(rx_string);
		if (match != null)
		{
			this.operand_str = match[1].replace("\"\"", "\"");
			this.pCurrPos += match[0].length;
			return true;
		}
		return false;
	};
	parserHelper.prototype.isName = function (formula, start_pos, wb, ws)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var subSTR = formula.substring(start_pos),
			match  = XRegExp.exec(subSTR, rx_name);

		if (match != null)
		{
			var name = match["name"];
			if (name && 0 !== name.length && name.toUpperCase() !== cBoolLocal.t && name.toUpperCase() !== cBoolLocal.f/*&& wb.DefinedNames && wb.isDefinedNamesExists( name, ws ? ws.getId() : null )*/)
			{
				this.pCurrPos += name.length;
				this.operand_str = name;
				return [true, name];
			}
			this.operand_str = name;
		}
		return [false];
	};
	parserHelper.prototype.isLeftBrace = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var code, find = false, length = formula.length;
		while (start_pos !== length)
		{
			code = formula.charCodeAt(start_pos);
			if (code === g_oCodeLeftBrace)
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				find = true;
				break;
			}
			else if (code === g_oCodeSpace)
			{
				++start_pos;
			}
			else
			{
				break;
			}
		}

		if (find)
		{
			while (start_pos !== length)
			{
				code = formula.charCodeAt(start_pos);
				if (code !== g_oCodeSpace)
				{
					break;
				}
				++start_pos;
			}
			this.pCurrPos = start_pos;
			return true;
		}
	};
	parserHelper.prototype.isRightBrace = function (formula, start_pos)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var code, find = false, length = formula.length;
		while (start_pos !== length)
		{
			code = formula.charCodeAt(start_pos);
			if (code === g_oCodeRightBrace)
			{
				this.operand_str = formula[start_pos];
				++start_pos;
				find = true;
				break;
			}
			else if (code === g_oCodeSpace)
			{
				++start_pos;
			}
			else
			{
				break;
			}
		}

		if (find)
		{
			while (start_pos !== length)
			{
				code = formula.charCodeAt(start_pos);
				if (code !== g_oCodeSpace)
				{
					break;
				}
				++start_pos;
			}
			this.pCurrPos = start_pos;
			return true;
		}
	};
	parserHelper.prototype.isTable = function (formula, start_pos, local)
	{
		if (this instanceof parserHelper)
		{
			this._reset();
		}

		var subSTR = formula.substring(start_pos),
			match  = XRegExp.exec(subSTR, local ? rx_table_local : rx_table);

		if (match != null && match["tableName"])
		{
			this.operand_str = match[0];
			this.pCurrPos += match[0].length;
			return match;
		}

		return false;
	};
// Парсим ссылку на диапазон в листе
	parserHelper.prototype.parse3DRef = function (formula)
	{
		// Сначала получаем лист
		var is3DRefResult = this.is3DRef(formula, 0);
		if (is3DRefResult && true === is3DRefResult[0])
		{
			// Имя листа в ссылке
			var sheetName = is3DRefResult[1];
			// Ищем начало range
			var indexStartRange = null !== this.pCurrPos ? this.pCurrPos : formula.indexOf("!") + 1;
			if (this.isArea(formula, indexStartRange) || this.isRef(formula, indexStartRange))
			{
				if (this.operand_str.length == formula.substring(indexStartRange).length)
					return {sheet: sheetName, sheet2: is3DRefResult[2], range: this.operand_str};
				else
					return null;
			}
		}
		// Возвращаем ошибку
		return null;
	};
// Возвращает ссылку на диапазон с листом (название листа экранируется)
	parserHelper.prototype.get3DRef = function (sheet, range)
	{
		sheet = sheet.split(":");
		var wsFrom = sheet[0],
			wsTo   = sheet[1] === undefined ? wsFrom : sheet[1];
		if (rx_test_ws_name.test(wsFrom) && rx_test_ws_name.test(wsTo))
		{
			return (wsFrom !== wsTo ? wsFrom + ":" + wsTo : wsFrom) + "!" + range;
		}
		else
		{
			wsFrom = wsFrom.replace(/'/g, "''");
			wsTo = wsTo.replace(/'/g, "''");
			return "'" + (wsFrom !== wsTo ? wsFrom + ":" + wsTo : wsFrom) + "'!" + range;
		}
	};
// Возвращает экранируемое название листа
	parserHelper.prototype.getEscapeSheetName = function (sheet)
	{
		return rx_test_ws_name.test(sheet) ? sheet : "'" + sheet.replace(/'/g, "''") + "'";
	};
	/**
	 * Проверяем ссылку на валидность для диаграммы или автофильтра
	 * @param {AscCommonExcel.Workbook} model
	 * @param {AscCommonExcel.WorkbookView} wb
	 * @param {Asc.c_oAscSelectionDialogType} dialogType
	 * @param {string} dataRange
	 * @param {boolean} fullCheck
	 * @param {boolean} isRows
	 * @param {Asc.c_oAscChartTypeSettings} chartType
	 * @returns {*}
	 */
	parserHelper.prototype.checkDataRange = function (model, wb, dialogType, dataRange, fullCheck, isRows, chartType)
	{
		var result, range, sheetModel;
		if (Asc.c_oAscSelectionDialogType.Chart === dialogType)
		{
			result = parserHelp.parse3DRef(dataRange);
			if (result)
			{
				sheetModel = model.getWorksheetByName(result.sheet);
				if (sheetModel)
				{
					range = AscCommonExcel.g_oRangeCache.getAscRange(result.range);
				}
			}
		}
		else
			range = AscCommonExcel.g_oRangeCache.getAscRange(dataRange);

		if (!range)
			return Asc.c_oAscError.ID.DataRangeError;

		if (fullCheck)
		{
			if (Asc.c_oAscSelectionDialogType.Chart === dialogType)
			{
				// Проверка максимального дипазона
				var maxSeries = 255;
				var minStockVal = 4;
				var maxValues = 4096;

				var intervalValues, intervalSeries;
				if (isRows)
				{
					intervalSeries = range.r2 - range.r1 + 1;
					intervalValues = range.c2 - range.c1 + 1;
				}
				else
				{
					intervalSeries = range.c2 - range.c1 + 1;
					intervalValues = range.r2 - range.r1 + 1;
				}

				if (Asc.c_oAscChartTypeSettings.stock === chartType)
				{
					var chartSettings = new Asc.asc_ChartSettings();
					chartSettings.putType(Asc.c_oAscChartTypeSettings.stock);
					chartSettings.putRange(dataRange);
					chartSettings.putInColumns(!isRows);
					var chartSeries = AscFormat.getChartSeries(sheetModel, chartSettings).series;
					if (minStockVal !== chartSeries.length || !chartSeries[0].Val || !chartSeries[0].Val.NumCache || chartSeries[0].Val.NumCache.length < minStockVal)
						return Asc.c_oAscError.ID.StockChartError;
				}
				else if (intervalSeries > maxSeries)
					return Asc.c_oAscError.ID.MaxDataSeriesError;
				else if(intervalValues > maxValues){
					return Asc.c_oAscError.ID.MaxDataPointsError;

				}
			}
			else if (Asc.c_oAscSelectionDialogType.FormatTable === dialogType)
			{
				// ToDo убрать эту проверку, заменить на более грамотную после правки функции _searchFilters
				if (true === wb.getWorksheet().model.autoFilters.isRangeIntersectionTableOrFilter(range))
					return Asc.c_oAscError.ID.AutoFilterDataRangeError;
			}
			else if (Asc.c_oAscSelectionDialogType.FormatTableChangeRange === dialogType)
			{
				// ToDo убрать эту проверку, заменить на более грамотную после правки функции _searchFilters
				var checkChangeRange = wb.getWorksheet().af_checkChangeRange(range);
				if (null !== checkChangeRange)
					return checkChangeRange;
			}
		}
		return Asc.c_oAscError.ID.No;
	};
	parserHelper.prototype.setDigitSeparator = function (sep)
	{
		if (sep != FormulaSeparators.digitSeparatorDef)
		{
			FormulaSeparators.digitSeparator = sep;
			FormulaSeparators.arrayRowSeparator = ";";
			FormulaSeparators.arrayColSeparator = "\\";
			FormulaSeparators.functionArgumentSeparator = ";";
			rx_number = new RegExp("^ *[+-]?\\d*(\\d|\\" + FormulaSeparators.digitSeparator + ")\\d*([eE][+-]?\\d+)?");
			rx_Comma = new RegExp("^ *[" + FormulaSeparators.functionArgumentSeparator + "] *");
			rx_arraySeparators = new RegExp("^ *[" + FormulaSeparators.arrayRowSeparator + "\\" + FormulaSeparators.arrayColSeparator + "] *");
		}
		else
		{
			FormulaSeparators.arrayRowSeparator = FormulaSeparators.arrayRowSeparatorDef;
			FormulaSeparators.arrayColSeparator = FormulaSeparators.arrayColSeparatorDef;
			FormulaSeparators.digitSeparator = FormulaSeparators.digitSeparatorDef;
			FormulaSeparators.functionArgumentSeparator = FormulaSeparators.functionArgumentSeparatorDef;
			rx_number = new RegExp("^ *[+-]?\\d*(\\d|\\" + FormulaSeparators.digitSeparatorDef + ")\\d*([eE][+-]?\\d+)?");
			rx_Comma = new RegExp("^ *[" + FormulaSeparators.functionArgumentSeparatorDef + "] *");
			rx_arraySeparators = new RegExp("^ *[" + FormulaSeparators.arrayRowSeparatorDef + "\\" + FormulaSeparators.arrayColSeparatorDef + "] *");
		}
		rx_table_local = build_rx_table_cur();
	};
	parserHelper.prototype.getColumnTypeByName = function (value)
	{
		var res;
		switch (value.toLowerCase())
		{
			case "#" + cStrucTableLocalColumns['a'].toLocaleLowerCase():
			case cStrucTableReservedWords.all.toLocaleLowerCase():
				res = FormulaTablePartInfo.all;
				break;
			case "#" + cStrucTableLocalColumns['d'].toLocaleLowerCase():
			case cStrucTableReservedWords.data.toLocaleLowerCase():
				res = FormulaTablePartInfo.data;
				break;
			case "#" + cStrucTableLocalColumns['h'].toLocaleLowerCase():
			case cStrucTableReservedWords.headers.toLocaleLowerCase():
				res = FormulaTablePartInfo.headers;
				break;
			case "#" + cStrucTableLocalColumns['t'].toLocaleLowerCase():
			case cStrucTableReservedWords.totals.toLocaleLowerCase():
				res = FormulaTablePartInfo.totals;
				break;
			case "#" + cStrucTableLocalColumns['tr'].toLocaleLowerCase():
			case cStrucTableReservedWords.at.toLocaleLowerCase():
			case cStrucTableReservedWords.thisrow.toLocaleLowerCase():
				res = FormulaTablePartInfo.thisRow;
				break;
			default:
				res = FormulaTablePartInfo.data;
				break;
		}
		return res;
	};
	parserHelper.prototype.getColumnNameByType = function (value, local)
	{
		switch (value)
		{
			case FormulaTablePartInfo.all:
			{
				if (local)
				{
					return "#" + cStrucTableLocalColumns['a'];
				}
				return cStrucTableReservedWords.all;
			}
			case FormulaTablePartInfo.data:
			{
				if (local)
				{
					return "#" + cStrucTableLocalColumns['d'];
				}
				return cStrucTableReservedWords.data;
			}
			case FormulaTablePartInfo.headers:
			{
				if (local)
				{
					return "#" + cStrucTableLocalColumns['h'];
				}
				return cStrucTableReservedWords.headers;
			}
			case FormulaTablePartInfo.totals:
			{
				if (local)
				{
					return "#" + cStrucTableLocalColumns['t'];
				}
				return cStrucTableReservedWords.totals;
			}
			case FormulaTablePartInfo.thisRow:
			{
				if (local)
				{
					return "#" + cStrucTableLocalColumns['tr'];
				}
				return cStrucTableReservedWords.thisrow;
			}
		}
		return null;
	};

	var parserHelp = new parserHelper();

	var g_oHtmlCursor = new CHTMLCursor();
	var kCurFormatPainterWord = 'de-formatpainter';
	g_oHtmlCursor.register(kCurFormatPainterWord, "text_copy", ["text_copy", 2, 11], "pointer");

	function asc_ajax(obj)
	{
		var url                                       = "", type                            = "GET",
			async                                     = true, data                        = null, dataType,
			error = null, success = null, httpRequest = null,
			contentType                               = "application/x-www-form-urlencoded",
			responseType = '',

			init                                      = function (obj)
			{
				if (typeof obj.url !== 'undefined')
				{
					url = obj.url;
				}
				if (typeof obj.type !== 'undefined')
				{
					type = obj.type;
				}
				if (typeof obj.async !== 'undefined')
				{
					async = obj.async;
				}
				if (typeof obj.data !== 'undefined')
				{
					data = obj.data;
				}
				if (typeof obj.dataType !== 'undefined')
				{
					dataType = obj.dataType;
				}
				if (typeof obj.error !== 'undefined')
				{
					error = obj.error;
				}
				if (typeof obj.success !== 'undefined')
				{
					success = obj.success;
				}
				if (typeof (obj.contentType) !== 'undefined')
				{
					contentType = obj.contentType;
				}
				if (typeof (obj.responseType) !== 'undefined')
				{
					responseType = obj.responseType;
				}

				if (window.XMLHttpRequest)
				{ // Mozilla, Safari, ...
					httpRequest = new XMLHttpRequest();
					if (httpRequest.overrideMimeType && dataType)
					{
						httpRequest.overrideMimeType(dataType);
					}
				}
				else if (window.ActiveXObject)
				{ // IE
					try
					{
						httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
					}
					catch (e)
					{
						try
						{
							httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
						}
						catch (e)
						{
						}
					}
				}

				httpRequest.onreadystatechange = function ()
				{
					respons(this);
				};
				send();
			},

			send                                      = function ()
			{
				httpRequest.open(type, url, async);
				if (type === "POST")
					httpRequest.setRequestHeader("Content-Type", contentType);
				if (responseType)
					httpRequest.responseType = responseType;
				httpRequest.send(data);
			},

			respons                                   = function (httpRequest)
			{
				switch (httpRequest.readyState)
				{
					case 0:
						// The object has been created, but not initialized (the open method has not been called).
						break;
					case 1:
						// A request has been opened, but the send method has not been called.
						break;
					case 2:
						// The send method has been called. No data is available yet.
						break;
					case 3:
						// Some data has been received; however, neither responseText nor responseBody is available.
						break;
					case 4:
						if (httpRequest.status === 200 || httpRequest.status === 1223)
						{
							if (typeof success === "function")
								success(httpRequest);
						}
						else
						{
							if (typeof error === "function")
								error(httpRequest, httpRequest.statusText, httpRequest.status);
						}
						break;
				}
			};

		init(obj);
	}


	function CIdCounter()
	{
		this.m_sUserId = null;
		this.m_bLoad = true;
		this.m_bRead = false;
		this.m_nIdCounterLoad = 0; // Счетчик Id для загрузки
		this.m_nIdCounterEdit = 0; // Счетчик Id для работы
	}

	CIdCounter.prototype.Get_NewId = function ()
	{
		if (true === this.m_bLoad || null === this.m_sUserId)
		{
			this.m_nIdCounterLoad++;
			return ("" + this.m_nIdCounterLoad);
		}
		else
		{
			this.m_nIdCounterEdit++;
			return ("" + this.m_sUserId + "_" + this.m_nIdCounterEdit);
		}
	};
	CIdCounter.prototype.Set_UserId = function (sUserId)
	{
		this.m_sUserId = sUserId;
	};
	CIdCounter.prototype.Set_Load = function (bValue)
	{
		this.m_bLoad = bValue;
	};
	CIdCounter.prototype.Clear = function ()
	{
		this.m_sUserId = null;
		this.m_bLoad = true;
		this.m_nIdCounterLoad = 0; // Счетчик Id для загрузки
		this.m_nIdCounterEdit = 0; // Счетчик Id для работы
	};

	function CLock()
	{
		this.Type = locktype_None;
		this.UserId = null;
	}

	CLock.prototype.Get_Type = function ()
	{
		return this.Type;
	};
	CLock.prototype.Set_Type = function (NewType, Redraw)
	{
		if (NewType === locktype_None)
			this.UserId = null;

		this.Type = NewType;

		var oApi = editor;
		var oLogicDocument = oApi.WordControl.m_oLogicDocument;
		if (false != Redraw && oLogicDocument)
		{
			// TODO: переделать перерисовку тут
			var oDrawingDocument = oLogicDocument.DrawingDocument;
			oDrawingDocument.ClearCachePages();
			oDrawingDocument.FirePaint();

			if(oApi.editorId === AscCommon.c_oEditorId.Presentation)
			{
				var oCurSlide = oLogicDocument.Slides[oLogicDocument.CurPage];
				if(oCurSlide && oCurSlide.notesShape && oCurSlide.notesShape.Lock === this)
				{
                    oDrawingDocument.Notes_OnRecalculate(oLogicDocument.CurPage, oCurSlide.NotesWidth, oCurSlide.getNotesHeight());
				}
			}
			// TODO: Обновлять интерфейс нужно, потому что мы можем стоять изначально в незалоченном объекте, а тут он
			//       может быть залочен.
			var oRevisionsStack = oApi.asc_GetRevisionsChangesStack();
			var arrParagraphs = [];
			for (var nIndex = 0, nCount = oRevisionsStack.length; nIndex < nCount; ++nIndex)
			{
				arrParagraphs.push(oRevisionsStack[nIndex].get_Paragraph())
			}

			var bNeedUpdate = false;
			for (var nIndex = 0, nCount = arrParagraphs.length; nIndex < nCount; ++nIndex)
			{
				if (arrParagraphs[nIndex].Get_Lock() === this)
				{
					bNeedUpdate = true;
					break;
				}
			}

			if (bNeedUpdate)
			{
				oLogicDocument.TrackRevisionsManager.Clear_VisibleChanges();
				oLogicDocument.Document_UpdateInterfaceState(false);
			}
		}
	};
	CLock.prototype.Check = function (Id)
	{
		if (this.Type === locktype_Mine)
			AscCommon.CollaborativeEditing.Add_CheckLock(false);
		else if (this.Type === locktype_Other || this.Type === locktype_Other2 || this.Type === locktype_Other3)
			AscCommon.CollaborativeEditing.Add_CheckLock(true);
		else
			AscCommon.CollaborativeEditing.Add_CheckLock(Id);
	};
	CLock.prototype.Lock = function (bMine)
	{
		if (locktype_None === this.Type)
		{
			if (true === bMine)
				this.Type = locktype_Mine;
			else
				true.Type = locktype_Other;
		}
	};
	CLock.prototype.Is_Locked = function ()
	{
		if (locktype_None != this.Type && locktype_Mine != this.Type)
			return true;

		return false;
	};
	CLock.prototype.Set_UserId = function (UserId)
	{
		this.UserId = UserId;
	};
	CLock.prototype.Get_UserId = function ()
	{
		return this.UserId;
	};
	CLock.prototype.Have_Changes = function ()
	{
		if (locktype_Other2 === this.Type || locktype_Other3 === this.Type)
			return true;

		return false;
	};


	function CContentChanges()
	{
		this.m_aChanges = [];
	}

	CContentChanges.prototype.Add = function (Changes)
	{
		this.m_aChanges.push(Changes);
	};
	CContentChanges.prototype.RemoveByHistoryItem = function (Item)
	{
		for (var nIndex = 0, nCount = this.m_aChanges.length; nIndex < nCount; ++nIndex)
		{
			if (this.m_aChanges[nIndex].m_pData === Item)
			{
				this.m_aChanges.splice(nIndex, 1);
				return;
			}
		}
	};
	CContentChanges.prototype.Clear = function ()
	{
		this.m_aChanges.length = 0;
	};
	CContentChanges.prototype.Check = function (Type, Pos)
	{
		var CurPos = Pos;
		var Count = this.m_aChanges.length;
		for (var Index = 0; Index < Count; Index++)
		{
			var NewPos = this.m_aChanges[Index].Check_Changes(Type, CurPos);
			if (false === NewPos)
				return false;

			CurPos = NewPos;
		}

		return CurPos;
	};
	CContentChanges.prototype.Refresh = function ()
	{
		var Count = this.m_aChanges.length;
		for (var Index = 0; Index < Count; Index++)
		{
			this.m_aChanges[Index].Refresh_BinaryData();
		}
	};

	function CContentChangesElement(Type, Pos, Count, Data)
	{
		this.m_nType = Type;  // Тип изменений (удаление или добавление)
		this.m_nCount = Count; // Количество добавленных/удаленных элементов
		this.m_pData = Data;  // Связанные с данным изменением данные из истории

		// Разбиваем сложное действие на простейшие
		this.m_aPositions = this.Make_ArrayOfSimpleActions(Type, Pos, Count);
	}

	CContentChangesElement.prototype.Refresh_BinaryData = function ()
	{
		var Binary_Writer = AscCommon.History.BinaryWriter;
		var Binary_Pos = Binary_Writer.GetCurPosition();

		this.m_pData.Data.UseArray = true;
		this.m_pData.Data.PosArray = this.m_aPositions;

		Binary_Writer.WriteString2(this.m_pData.Class.Get_Id());
		Binary_Writer.WriteLong(this.m_pData.Data.Type);
		this.m_pData.Data.WriteToBinary(Binary_Writer);

		var Binary_Len = Binary_Writer.GetCurPosition() - Binary_Pos;

		this.m_pData.Binary.Pos = Binary_Pos;
		this.m_pData.Binary.Len = Binary_Len;
	};
	CContentChangesElement.prototype.Check_Changes = function (Type, Pos)
	{
		var CurPos = Pos;
		if (contentchanges_Add === Type)
		{
			for (var Index = 0; Index < this.m_nCount; Index++)
			{
				if (false !== this.m_aPositions[Index])
				{
					if (CurPos <= this.m_aPositions[Index])
						this.m_aPositions[Index]++;
					else
					{
						if (contentchanges_Add === this.m_nType)
							CurPos++;
						else //if ( contentchanges_Remove === this.m_nType )
							CurPos--;
					}
				}
			}
		}
		else //if ( contentchanges_Remove === Type )
		{
			for (var Index = 0; Index < this.m_nCount; Index++)
			{
				if (false !== this.m_aPositions[Index])
				{
					if (CurPos < this.m_aPositions[Index])
						this.m_aPositions[Index]--;
					else if (CurPos > this.m_aPositions[Index])
					{
						if (contentchanges_Add === this.m_nType)
							CurPos++;
						else //if ( contentchanges_Remove === this.m_nType )
							CurPos--;
					}
					else //if ( CurPos === this.m_aPositions[Index] )
					{
						if (AscCommon.contentchanges_Remove === this.m_nType)
						{
							// Отмечаем, что действия совпали
							this.m_aPositions[Index] = false;
							return false;
						}
						else
						{
							CurPos++;
						}
					}
				}
			}
		}

		return CurPos;
	};
	CContentChangesElement.prototype.Make_ArrayOfSimpleActions = function (Type, Pos, Count)
	{
		// Разбиваем действие на простейшие
		var Positions = [];
		if (contentchanges_Add === Type)
		{
			for (var Index = 0; Index < Count; Index++)
				Positions[Index] = Pos + Index;
		}
		else //if ( contentchanges_Remove === Type )
		{
			for (var Index = 0; Index < Count; Index++)
				Positions[Index] = Pos;
		}

		return Positions;
	};


	/**
	 * Корректируем заданное значение в миллиметрах к ближайшему целому значению в твипсах
	 * @param mm - заданное значение в миллиметрах
	 * @returns {number} - получаем новое значение в миллиметрах, являющееся целым значением в твипсах
	 */
	function CorrectMMToTwips(mm)
	{
		return (((mm * 20 * 72 / 25.4) + 0.5) | 0) * 25.4 / 20 / 72;
	}
	/**
	 * Получаем значение в миллиметрах заданного количества твипсов
	 * @param nTwips[=1] - значение в твипсах
	 * @returns {number}
	 */
	function TwipsToMM(nTwips)
	{
		return (null !== nTwips && undefined !== nTwips ? nTwips : 1) * 25.4 / 20 / 72;
	}

	/**
	 * Конвертируем миллиметры в ближайшее целое значение твипсов
	 * @param mm - значение в миллиметрах
	 * @returns {number}
	 */
	function MMToTwips(mm)
	{
		return (((mm * 20 * 72 / 25.4) + 0.5) | 0);
	}

	/**
	 * Конвертируем число из римской системы исчисления в обычное десятичное число
	 * @param sRoman {string}
	 * @returns {number}
	 */
	function RomanToInt(sRoman)
	{
		sRoman = sRoman.toUpperCase();
		if (sRoman < 1)
		{
			return 0;
		}
		else if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/i.test(sRoman))
		{
			return NaN;
		}

		var chars  = {
			"M"  : 1000,
			"CM" : 900,
			"D"  : 500,
			"CD" : 400,
			"C"  : 100,
			"XC" : 90,
			"L"  : 50,
			"XL" : 40,
			"X"  : 10,
			"IX" : 9,
			"V"  : 5,
			"IV" : 4,
			"I"  : 1
		};
		var arabic = 0;
		sRoman.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function(i)
		{
			arabic += chars[i];
		});

		return arabic;
	}

	/**
	 * Конвертируем нумерацию {a b ... z aa bb ... zz aaa bbb ... zzz ...} в число
	 * @param sLetters
	 * @constructor
	 */
	function LatinNumberingToInt(sLetters)
	{
		sLetters = sLetters.toUpperCase();

		if (sLetters.length <= 0)
			return NaN;

		var nLen = sLetters.length;

		var nFirstCharCode = sLetters.charCodeAt(0);
		if (65 > nFirstCharCode || nFirstCharCode > 90)
			return NaN;

		for (var nPos = 1; nPos < nLen; ++nPos)
		{
			if (sLetters.charCodeAt(nPos) !== nFirstCharCode)
				return NaN;
		}

		return (nFirstCharCode - 64) + 26 * (nLen - 1);
	}

	var g_oUserColorById = {}, g_oUserNextColorIndex = 0;

	function getUserColorById(userId, userName, isDark, isNumericValue)
	{
		if ((!userId || "" === userId) && (!userName || "" === userName))
			return new CColor(0, 0, 0, 255);

		var res;
		if (g_oUserColorById.hasOwnProperty(userId))
		{
			res = g_oUserColorById[userId];
		}
		else if (g_oUserColorById.hasOwnProperty(userName))
		{
			res = g_oUserColorById[userName];
		}
		else
		{
			var nColor = Asc.c_oAscArrUserColors[g_oUserNextColorIndex % Asc.c_oAscArrUserColors.length];
			++g_oUserNextColorIndex;

			res = g_oUserColorById[userId || userName] = new CUserCacheColor(nColor);
		}

		if (!res)
			return new CColor(0, 0, 0, 255);

		var oColor = true === isDark ? res.Dark : res.Light;
		return true === isNumericValue ? ((oColor.r << 16) & 0xFF0000) | ((oColor.g << 8) & 0xFF00) | (oColor.b & 0xFF) : oColor;
	}

	function isNullOrEmptyString(str)
	{
		return (str == undefined) || (str == null) || (str == "");
	}

	function unleakString(s) {
		//todo remove in the future
		//https://bugs.chromium.org/p/v8/issues/detail?id=2869
		return (' ' + s).substr(1);
	}

	function CUserCacheColor(nColor)
	{
		this.Light = null;
		this.Dark = null;
		this.init(nColor);
	}

	CUserCacheColor.prototype.init = function (nColor)
	{
		var r = (nColor >> 16) & 0xFF;
		var g = (nColor >> 8) & 0xFF;
		var b = nColor & 0xFF;

		var Y = Math.max(0, Math.min(255, 0.299 * r + 0.587 * g + 0.114 * b));
		var Cb = Math.max(0, Math.min(255, 128 - 0.168736 * r - 0.331264 * g + 0.5 * b));
		var Cr = Math.max(0, Math.min(255, 128 + 0.5 * r - 0.418688 * g - 0.081312 * b));

		if (Y > 63)
			Y = 63;

		var R = Math.max(0, Math.min(255, Y + 1.402 * (Cr - 128))) | 0;
		var G = Math.max(0, Math.min(255, Y - 0.34414 * (Cb - 128) - 0.71414 * (Cr - 128))) | 0;
		var B = Math.max(0, Math.min(255, Y + 1.772 * (Cb - 128))) | 0;

		this.Light = new CColor(r, g, b, 255);
		this.Dark = new CColor(R, G, B, 255);
	};

	function loadScript(url, onSuccess, onError)
	{
		if (window["NATIVE_EDITOR_ENJINE"] === true || window["Native"] !== undefined)
		{
			onSuccess();
			return;
		}

		if (window["AscDesktopEditor"] && window["local_load_add"])
		{
			var _context = {
				"completeLoad": function ()
								{
									return onSuccess();
								}
			};
			window["local_load_add"](_context, "sdk-all-from-min", url);
			var _ret_param = window["AscDesktopEditor"]["LoadJS"](url);
			if (2 != _ret_param)
				window["local_load_remove"](url);
			if (_ret_param == 1)
			{
				setTimeout(onSuccess, 1);
				return;
			}
			else if (_ret_param == 2)
				return;
		}

		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = url;
		script.onload = onSuccess;
		script.onerror = onError;

		// Fire the loading
		document.head.appendChild(script);
	}

	function loadSdk(sdkName, onSuccess, onError)
	{
		if (window['AscNotLoadAllScript'])
		{
			onSuccess();
		}
		else
		{
			loadScript('./../../../../sdkjs/' + sdkName + '/sdk-all.js', onSuccess, onError);
		}
	}

	function getAltGr(e)
	{
		var ctrlKey = e.metaKey || e.ctrlKey;
		var altKey = e.altKey;
		return (altKey && (AscBrowser.isMacOs ? !ctrlKey : ctrlKey));
	}

	function getColorThemeByIndex(index)
	{
		var _c, scheme = null;
		var oColorScheme = AscCommon.g_oUserColorScheme;
		if (index >= oColorScheme.length)
		{
			return scheme;
		}
		scheme = new AscFormat.ClrScheme();

		var tmp = oColorScheme[index];
		scheme.name = tmp.name;

		_c = tmp.get_dk1();
		scheme.colors[8] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_lt1();
		scheme.colors[12] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_dk2();
		scheme.colors[9] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_lt2();
		scheme.colors[13] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent1();
		scheme.colors[0] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent2();
		scheme.colors[1] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent3();
		scheme.colors[2] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent4();
		scheme.colors[3] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent5();
		scheme.colors[4] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_accent6();
		scheme.colors[5] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_hlink();
		scheme.colors[11] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);
		_c = tmp.get_folHlink();
		scheme.colors[10] = AscFormat.CreateUniColorRGB(_c.r, _c.g, _c.b);

		return scheme;
	}

	function isEastAsianScript(value)
	{
		// Bopomofo (3100–312F)
		// Bopomofo Extended (31A0–31BF)
		// CJK Unified Ideographs (4E00–9FEA)
		// CJK Unified Ideographs Extension A (3400–4DB5)
		// CJK Unified Ideographs Extension B (20000–2A6D6)
		// CJK Unified Ideographs Extension C (2A700–2B734)
		// CJK Unified Ideographs Extension D (2B740–2B81D)
		// CJK Unified Ideographs Extension E (2B820–2CEA1)
		// CJK Unified Ideographs Extension F (2CEB0–2EBE0)
		// CJK Compatibility Ideographs (F900–FAFF)
		// CJK Compatibility Ideographs Supplement (2F800–2FA1F)
		// Kangxi Radicals (2F00–2FDF)
		// CJK Radicals Supplement (2E80–2EFF)
		// CJK Strokes (31C0–31EF)
		// Ideographic Description Characters (2FF0–2FFF)
		// Hangul Jamo (1100–11FF)
		// Hangul Jamo Extended-A (A960–A97F)
		// Hangul Jamo Extended-B (D7B0–D7FF)
		// Hangul Compatibility Jamo (3130–318F)
		// Halfwidth and Fullwidth Forms (FF00–FFEF)
		// Hangul Syllables (AC00–D7AF)
		// Hiragana (3040–309F)
		// Kana Extended-A (1B100–1B12F)
		// Kana Supplement (1B000–1B0FF)
		// Kanbun (3190–319F)
		// Katakana (30A0–30FF)
		// Katakana Phonetic Extensions (31F0–31FF)
		// Lisu (A4D0–A4FF)
		// Miao (16F00–16F9F)
		// Nushu (1B170–1B2FF)
		// Tangut (17000–187EC)
		// Tangut Components (18800–18AFF)
		// Yi Syllables (A000–A48F)
		// Yi Radicals (A490–A4CF)

		return ((0x3100 <= value && value <= 0x312F)
			|| (0x31A0 <= value && value <= 0x31BF)
			|| (0x4E00 <= value && value <= 0x9FEA)
			|| (0x3400 <= value && value <= 0x4DB5)
			|| (0x20000 <= value && value <= 0x2A6D6)
			|| (0x2A700 <= value && value <= 0x2B734)
			|| (0x2B740 <= value && value <= 0x2B81D)
			|| (0x2B820 <= value && value <= 0x2CEA1)
			|| (0x2CEB0 <= value && value <= 0x2EBE0)
			|| (0xF900 <= value && value <= 0xFAFF)
			|| (0x2F800 <= value && value <= 0x2FA1F)
			|| (0x2F00 <= value && value <= 0x2FDF)
			|| (0x2E80 <= value && value <= 0x2EFF)
			|| (0x31C0 <= value && value <= 0x31EF)
			|| (0x2FF0 <= value && value <= 0x2FFF)
			|| (0x1100 <= value && value <= 0x11FF)
			|| (0xA960 <= value && value <= 0xA97F)
			|| (0xD7B0 <= value && value <= 0xD7FF)
			|| (0x3130 <= value && value <= 0x318F)
			|| (0xFF00 <= value && value <= 0xFFEF)
			|| (0xAC00 <= value && value <= 0xD7AF)
			|| (0x3040 <= value && value <= 0x309F)
			|| (0x1B100 <= value && value <= 0x1B12F)
			|| (0x1B000 <= value && value <= 0x1B0FF)
			|| (0x3190 <= value && value <= 0x319F)
			|| (0x30A0 <= value && value <= 0x30FF)
			|| (0x31F0 <= value && value <= 0x31FF)
			|| (0xA4D0 <= value && value <= 0xA4FF)
			|| (0x16F00 <= value && value <= 0x16F9F)
			|| (0x1B170 <= value && value <= 0x1B2FF)
			|| (0x17000 <= value && value <= 0x187EC)
			|| (0x18800 <= value && value <= 0x18AFF)
			|| (0xA000 <= value && value <= 0xA48F)
			|| (0xA490 <= value && value <= 0xA4CF));
	}

	var g_oIdCounter = new CIdCounter();

	window["SetDoctRendererParams"] = function (_params)
	{
		if (_params["retina"] === true)
			AscBrowser.isRetina = true;
	};

	window.Asc.g_signature_drawer = null;
	function CSignatureDrawer(id, api, w, h)
	{
		window.Asc.g_signature_drawer = this;

		this.Api = api;
		this.CanvasParent = document.getElementById(id);

		this.Canvas = document.createElement('canvas');
		this.Canvas.style.position = "absolute";
		this.Canvas.style.left = "0px";
		this.Canvas.style.top = "0px";

		var _width = parseInt(this.CanvasParent.offsetWidth);
		var _height = parseInt(this.CanvasParent.offsetHeight);
		if (0 == _width)
			_width = 300;
		if (0 == _height)
			_height = 80;

		this.Canvas.width = _width;
		this.Canvas.height = _height;

		this.CanvasParent.appendChild(this.Canvas);

		this.Image = "";
		this.ImageHtml = null;

		this.Text = "";
		this.Font = "Arial";
		this.Size = 10;
		this.Italic = true;
		this.Bold = false;

		this.Width = w;
		this.Height = h;

		this.CanvasReturn = null;

		this.IsAsync = false;
	}

	CSignatureDrawer.prototype.getCanvas = function()
	{
		return (this.CanvasReturn == null) ? this.Canvas : this.CanvasReturn;
	};

	CSignatureDrawer.prototype.getImages = function()
	{
		if (!this.isValid())
			return ["", ""];

		this.CanvasReturn = document.createElement("canvas");
		this.CanvasReturn.width = (this.Width * AscCommon.g_dKoef_mm_to_pix);
		this.CanvasReturn.height = (this.Height * AscCommon.g_dKoef_mm_to_pix);

		if (this.Text != "")
			this.drawText();
		else
			this.drawImage();

		var _ret = [];
		_ret.push(this.CanvasReturn.toDataURL("image/png"));

		var _ctx = this.CanvasReturn.getContext("2d");
		_ctx.strokeStyle = "#FF0000";
		_ctx.lineWidth = 2;

		_ctx.moveTo(0, 0);
		_ctx.lineTo(this.CanvasReturn.width, this.CanvasReturn.height);
		_ctx.moveTo(0, this.CanvasReturn.height);
		_ctx.lineTo(this.CanvasReturn.width, 0);

		_ctx.stroke();

		_ret.push(this.CanvasReturn.toDataURL("image/png"));

		this.CanvasReturn = null;
		return _ret;
	};

	CSignatureDrawer.prototype.setText = function(text, font, size, isItalic, isBold)
	{
		if (this.IsAsync)
		{
			this.Text = text;
			return;
		}

		this.Image = "";
		this.ImageHtml = null;

		this.Text = text;
		this.Font = font;
		this.Size = size;
		this.Italic = isItalic;
		this.Bold = isBold;

		this.IsAsync = true;
        AscFonts.FontPickerByCharacter.checkText(this.Text, this, function() {

        	this.IsAsync = false;

            var loader     = AscCommon.g_font_loader;
            var fontinfo   = AscFonts.g_fontApplication.GetFontInfo(font);
            var isasync    = loader.LoadFont(fontinfo, function() {
                window.Asc.g_signature_drawer.Api.sync_EndAction(Asc.c_oAscAsyncActionType.Information, Asc.c_oAscAsyncAction.LoadFont);
                window.Asc.g_signature_drawer.drawText();
            });

            if (false === isasync)
            {
                this.drawText();
            }

        });
	};

	CSignatureDrawer.prototype.drawText = function()
	{
        var _oldTurn = this.Api.isViewMode;
        var _oldMarks = this.Api.ShowParaMarks;
        this.Api.isViewMode = true;
        this.Api.ShowParaMarks = false;
		AscFormat.ExecuteNoHistory(AscCommon.DrawTextByCenter, this, []);
        this.Api.isViewMode = _oldTurn;
        this.Api.ShowParaMarks = _oldMarks;
	};

	CSignatureDrawer.prototype.drawImage = function()
	{
		var _canvas = this.getCanvas();
		var w = _canvas.width;
		var h = _canvas.height;
		var _ctx = _canvas.getContext("2d");
		_ctx.clearRect(0, 0, w, h);

		var im_w = this.ImageHtml.width;
		var im_h = this.ImageHtml.height;

		var _x = 0;
		var _y = 0;
		var _w = 0;
		var _h = 0;

		var koef1 = w / h;
		var koef2 = im_w / im_h;

		if (koef1 > koef2)
		{
			_h = h;
			_w = (koef2 * _h) >> 0;
			_y = 0;
			_x = (w - _w) >> 1;
		}
		else
		{
			_w = w;
			_h = (_w / koef2) >> 0;
			_x = 0;
			_y = (h - _h) >> 1;
		}

		_ctx.drawImage(this.ImageHtml, _x, _y, _w, _h);
	};

	CSignatureDrawer.prototype.selectImage = CSignatureDrawer.prototype["selectImage"] = function()
	{
		this.Text = "";
		window["AscDesktopEditor"]["OpenFilenameDialog"]("images", false, function(_file) {
            var file = _file;
            if (Array.isArray(file))
                file = file[0];

			if (file == "")
                return;

            var _drawer = window.Asc.g_signature_drawer;
            _drawer.Image = window["AscDesktopEditor"]["GetImageBase64"](file);

            _drawer.ImageHtml = new Image();
            _drawer.ImageHtml.onload = function()
            {
                window.Asc.g_signature_drawer.drawImage();
            };
            _drawer.ImageHtml.src = _drawer.Image;
            _drawer = null;
		});
	};

	CSignatureDrawer.prototype.isValid = function()
	{
		return (this.Image != "" || this.Text != "");
	};

	CSignatureDrawer.prototype.destroy = function()
	{
		window.Asc.g_signature_drawer.CanvasParent.removeChild(this.Canvas);
		delete window.Asc.g_signature_drawer;
	};

	function CSignatureImage()
	{
		this.ImageValidBase64 = "";
		this.ImageInvalidBase64 = "";

		this.ImageValid = null;
		this.ImageInvalid = null;

		this.Valid = false;
		this.Loading = 0;

		this.Remove = function()
		{
			this.ImageValidBase64 = "";
			this.ImageInvalidBase64 = "";

			this.ImageValid = null;
			this.ImageInvalid = null;

			this.Valid = false;
			this.Loading = 0;
		};

		this.Register = function(_api, _guid)
		{
			if (_api.ImageLoader.map_image_index[_guid])
				return;
			var _obj = { Image : (this.Valid ? this.ImageValid : this.ImageInvalid), Status : ImageLoadStatus.Complete, src : _guid };
			_api.ImageLoader.map_image_index[_guid] = _obj;
		};

		this.Unregister = function(api, _guid)
		{
			if (_api.ImageLoader.map_image_index[_guid])
				delete _api.ImageLoader.map_image_index[_guid];
		};
	}

    /////////////////////////////////////////////////////////
	///////////////       CRYPT      ////////////////////////
	/////////////////////////////////////////////////////////
    AscCommon.EncryptionMessageType = {
        Encrypt : 0,
        Decrypt : 1
    };
    function CEncryptionData()
    {
    	this._init = false;

        this.arrData = [];
        this.arrImages = [];

        this.handleChangesCallback = null;
        this.isChangesHandled = false;

        this.cryptoMode = 0; // start crypto mode
		this.isChartEditor = false;

        this.isExistDecryptedChanges = false; // был ли хоть один запрос на расшифровку данных (были ли чужие изменения)

        this.cryptoPrefix = (window["AscDesktopEditor"] && window["AscDesktopEditor"]["GetEncryptedHeader"]) ? window["AscDesktopEditor"]["GetEncryptedHeader"]() : "ENCRYPTED;";
        this.cryptoPrefixLen = this.cryptoPrefix.length;

        this.editorId = null;

        this.nextChangesTimeoutId = -1;

        this.isPasswordCryptoPresent = false;

        this.init = function()
		{
			this._init = true;
		};

        this.isInit = function()
        {
			return this._init;
        };

        this.isNeedCrypt = function()
		{
			if (!window.g_asc_plugins)
				return false;

            if (!window.g_asc_plugins.isRunnedEncryption())
                return false;

            if (!window["AscDesktopEditor"])
                return false;

            if (this.isChartEditor)
            	return false;

            if (2 == this.cryptoMode)
            	return true;

            if (0 === window["AscDesktopEditor"]["CryptoMode"])
            	return false;

            return true;
		};

		this.isCryptoImages = function()
		{
            return (this.isNeedCrypt() && this.isPasswordCryptoPresent);
		};

        this.addCryproImagesFromDialog = function(callback)
		{
			var _this = this;
            window["AscDesktopEditor"]["OpenFilenameDialog"]("images", true, function(files) {
				var _files = [];

				var _options = { isImageCrypt: true, callback: callback, ext : [] };

				for (var i = 0; i < files.length; i++)
				{
                    _files.push(window["AscDesktopEditor"]["GetImageBase64"](files[i], true));
                    _options.ext.push(AscCommon.GetFileExtension(files[i]));
				}

				_this.sendChanges(this, _files, AscCommon.EncryptionMessageType.Encrypt, _options);
            });
		};

        this.addCryproImagesFromUrls = function(urls, callback)
        {
            var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
            _editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.LoadImage);

            var _this = this;
            window["AscDesktopEditor"]["DownloadFiles"](urls, [], function(files) {

            	_editor.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.LoadImage);

                _editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage);

            	var _files = [];

                var _options = { isImageCrypt: true, isUrls: true, callback: callback, ext : [], api: _editor };

                for (var elem in files)
                {
                    _files.push(window["AscDesktopEditor"]["GetImageBase64"](files[elem], true));
                    _options.ext.push(window["AscDesktopEditor"]["GetImageFormat"](files[elem]));
                    window["AscDesktopEditor"]["RemoveFile"](files[elem]);
                }

                _this.sendChanges(this, _files, AscCommon.EncryptionMessageType.Encrypt, _options);
            });
        };

        this.onDecodeError = function()
		{
            var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
			_editor.sendEvent("asc_onError", Asc.c_oAscError.ID.DataEncrypted, Asc.c_oAscError.Level.Critical);
		};

        this.checkEditorId = function()
		{
            if (null == this.editorId)
            {
                var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
                this.editorId = _editor.editorId;
            }
		};

        this.decryptImage = function(src, img, data)
        {
            this.sendChanges(this, [data], AscCommon.EncryptionMessageType.Decrypt, { isImageDecrypt: true, src: src, img : img });
        };

        this.nextChanges = function()
		{
            this.nextChangesTimeoutId = setTimeout(function() {
				AscCommon.EncryptionWorker.sendChanges(undefined, undefined);
                this.nextChangesTimeoutId = -1;
			}, 10);
		};

        this.sendChanges = function(sender, data, type, options)
        {
            if (!this.isNeedCrypt())
            {
                if (AscCommon.EncryptionMessageType.Encrypt == type)
                {
                    sender._send(data, true);
                }
                else if (AscCommon.EncryptionMessageType.Decrypt == type)
                {
                    if (this.isExistEncryptedChanges(data["changes"]))
                    {
                        this.onDecodeError();
                        return;
                    }
                    sender._onSaveChanges(data, true);
                }
                return;
            }

            if (undefined !== type)
                this.arrData.push({ sender: sender, type: type, data: data, options: options });

            if (this.arrData.length == 0)
                return;

            if (undefined !== type && ((1 != this.arrData.length) || !this.isChangesHandled))
            	return; // вызовется на коллбэке

			if (undefined !== type && -1 != this.nextChangesTimeoutId)
			{
				// вызвали send, когда данные на receiveChanges были удалены - и запустился nextChanges
				// но так как он сделан на таймере - то просто он не успел отработать.
				// тут запускаем единственное изменение - это и есть как бы next.
				// убиваем таймер

				clearTimeout(this.nextChangesTimeoutId);
				this.nextChangesTimeoutId = -1;
			}

            if (AscCommon.EncryptionMessageType.Encrypt == this.arrData[0].type)
            {
            	//console.log("encrypt: " + data["changes"]);
				if (this.arrData[0].options && this.arrData[0].options.isImageCrypt)
                    window.g_asc_plugins.sendToEncryption({ "type" : "encryptData", "data" : this.arrData[0].data });
				else
                    window.g_asc_plugins.sendToEncryption({ "type" : "encryptData", "data" : JSON.parse(this.arrData[0].data["changes"]) });
            }
            else if (AscCommon.EncryptionMessageType.Decrypt == this.arrData[0].type)
            {
                //console.log("decrypt: " + data["changes"]);
                if (this.arrData[0].options && this.arrData[0].options.isImageDecrypt)
                    window.g_asc_plugins.sendToEncryption({ "type" : "decryptData", "data" : this.arrData[0].data });
                else
                    window.g_asc_plugins.sendToEncryption({ "type" : "decryptData", "data" : this.arrData[0].data["changes"] });
            }
        };

        this.receiveChanges = function(obj)
        {
        	var data = obj["data"];
        	var check = obj["check"];
        	if (!check)
			{
				this.onDecodeError();
				return;
			}

        	if (this.handleChangesCallback)
			{
                this.isExistDecryptedChanges = true;
                this.checkEditorId();

				if (this.editorId == AscCommon.c_oEditorId.Spreadsheet)
				{
                    for (var i = data.length - 1; i >= 0; i--)
                    {
                        this.handleChangesCallback.changesBase[i] = data[i];
                    }
                }
                else
				{
                    for (var i = data.length - 1; i >= 0; i--)
                    {
                        this.handleChangesCallback.changesBase[i].m_pData = data[i];
                    }
				}
                this.isChangesHandled = true;
				this.handleChangesCallback.callback.call(this.handleChangesCallback.sender);
				this.handleChangesCallback = null;

                this.nextChanges();
				return;
			}

        	var obj = this.arrData[0];
        	this.arrData.splice(0, 1);

            if (AscCommon.EncryptionMessageType.Encrypt == obj.type)
            {
            	if (obj.options && obj.options.isImageCrypt)
				{
                    for (var i = 0; i < data.length; i++)
					{
						if (this.cryptoPrefix == data[i].substr(0, this.cryptoPrefixLen))
						{
							// дописываем extension
                            data[i] = this.cryptoPrefix + obj.options.ext[i] + ";" + data[i].substr(this.cryptoPrefixLen);
						}
					}

					if (!obj.options.isUrls)
						obj.options.callback(Asc.c_oAscError.ID.No, data);
					else
					{
						AscCommon.UploadImageUrls(data, obj.options.api.documentId, obj.options.api.documentUserId, obj.options.api.CoAuthoringApi.get_jwt(), function(urls)
                        {
                            obj.options.api.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.UploadImage);

                            obj.options.callback(urls);
                        });
					}
				}
				else
				{
                    obj.data["changes"] = JSON.stringify(data);
                    obj.sender._send(obj.data, true);
                }
            }
            else if (AscCommon.EncryptionMessageType.Decrypt == obj.type)
            {
                if (obj.options && obj.options.isImageDecrypt)
                {
                	window["AscDesktopEditor"]["ResaveFile"](obj.options.src, data[0]);
                    obj.options.img["onload_crypto"](obj.options.src);
                }
                else
				{
                    this.isExistDecryptedChanges = true;
                    obj.data["changes"] = data;
                    obj.sender._onSaveChanges(obj.data, true);
                }
            }

            this.nextChanges();
        };

        this.isExistEncryptedChanges = function(_array)
		{
			if (0 == _array.length)
				return false;

			this.checkEditorId();

			var isChangesMode = (_array[0]["change"]) ? true : false;
			var _prefix = "";
			var _checkPrefixLen = this.cryptoPrefixLen + 1; // "ENCRYPTED; && ""ENCRYPTED;

			if (isChangesMode)
			{
                for (var i = _array.length - 1; i >= 0; i--)
                {
                    if (_array[i]["change"].length > _checkPrefixLen)
                    {
                    	_prefix = _array[i]["change"].substr(0, _checkPrefixLen);
                        if (-1 != _prefix.indexOf(this.cryptoPrefix))
                        {
                            isCrypted = true;
                            break;
                        }
                    }
                }

                return isCrypted;
			}

            var isCrypted = false;
            if (this.editorId == AscCommon.c_oEditorId.Spreadsheet)
            {
                for (var i = _array.length - 1; i >= 0; i--)
                {
                    if (_array[i].length > _checkPrefixLen)
                    {
                        _prefix = _array[i].substr(0, _checkPrefixLen);
                        if (-1 != _prefix.indexOf(this.cryptoPrefix))
                        {
                            isCrypted = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                for (var i = _array.length - 1; i >= 0; i--)
                {
                    if (_array[i].m_pData.length > _checkPrefixLen)
                    {
                        _prefix = _array[i].m_pData.substr(0, _checkPrefixLen);
                        if (-1 != _prefix.indexOf(this.cryptoPrefix))
                        {
                            isCrypted = true;
                            break;
                        }
                    }
                }
            }
            return isCrypted;
		};

        this.handleChanges = function(_array, _sender, _callback)
		{
            if (0 == _array.length || !this.isNeedCrypt())
			{
				if (this.isExistEncryptedChanges(_array))
				{
					this.onDecodeError();
					return;
				}

				this.isChangesHandled = true;
				_callback.call(_sender);
                return;
			}

			this.handleChangesCallback = { changesBase : _array, changes : [], sender : _sender, callback : _callback };

			this.checkEditorId();

            if (this.editorId == AscCommon.c_oEditorId.Spreadsheet)
            {
                for (var i = _array.length - 1; i >= 0; i--)
                {
                    this.handleChangesCallback.changes[i] = _array[i];
                }
            }
            else
			{
                for (var i = _array.length - 1; i >= 0; i--)
                {
                    this.handleChangesCallback.changes[i] = _array[i].m_pData;
                }
			}

            window.g_asc_plugins.sendToEncryption({ "type" : "decryptData", "data" : this.handleChangesCallback.changes });
		};

        this.asc_setAdvancedOptions = function(api, idOption, option)
		{
            if (window.isNativeOpenPassword)
            {
                window["AscDesktopEditor"]["NativeViewerOpen"](option.asc_getPassword());
                return;
            }
            if (window.isCloudCryptoDownloadAs)
            	return false;

			if (!this.isNeedCrypt())
				return false;

            window.checkPasswordFromPlugin = true;
            if (window["Asc"].c_oAscAdvancedOptionsID.TXT === idOption)
            {
                var _param = ("<m_nCsvTxtEncoding>" + option.asc_getCodePage() + "</m_nCsvTxtEncoding>");
                window["AscDesktopEditor"]["SetAdvancedOptions"](_param);
            }
            else if (window["Asc"].c_oAscAdvancedOptionsID.CSV === idOption)
            {
                var delimiter = option.asc_getDelimiter();
                var delimiterChar = option.asc_getDelimiterChar();
                var _param = "";
                _param += ("<m_nCsvTxtEncoding>" + option.asc_getCodePage() + "</m_nCsvTxtEncoding>");
                if (null != delimiter) {
                    _param += ("<m_nCsvDelimiter>" + delimiter + "</m_nCsvDelimiter>");
                }
                if (null != delimiterChar) {
                    _param += ("<m_nCsvDelimiterChar>" + delimiterChar + "</m_nCsvDelimiterChar>");
                }

                window["AscDesktopEditor"]["SetAdvancedOptions"](_param);
            }
            else if (window["Asc"].c_oAscAdvancedOptionsID.DRM === idOption)
            {
                var _param = ("<m_sPassword>" + AscCommon.CopyPasteCorrectString(option.asc_getPassword()) + "</m_sPassword>");
                api.currentPassword = option.asc_getPassword();
                window["AscDesktopEditor"]["SetAdvancedOptions"](_param);
            }
            return true;
		};
    }

    AscCommon.EncryptionWorker = new CEncryptionData();

	/** @constructor */
	function CTranslateManager()
	{
		this.mapTranslate = {};
	}

	CTranslateManager.prototype.init = function(map)
	{
		this.mapTranslate = map || {};
	};
	CTranslateManager.prototype.getValue = function(key)
	{
		return this.mapTranslate.hasOwnProperty(key) ? this.mapTranslate[key] : key;
	};
	//------------------------------------------------------------fill polyfill--------------------------------------------
	if (!Array.prototype.fill) {
		Object.defineProperty(Array.prototype, 'fill', {
			value: function(value) {

				// Steps 1-2.
				if (this == null) {
					throw new TypeError('this is null or not defined');
				}

				var O = Object(this);

				// Steps 3-5.
				var len = O.length >>> 0;

				// Steps 6-7.
				var start = arguments[1];
				var relativeStart = start >> 0;

				// Step 8.
				var k = relativeStart < 0 ?
					Math.max(len + relativeStart, 0) :
					Math.min(relativeStart, len);

				// Steps 9-10.
				var end = arguments[2];
				var relativeEnd = end === undefined ?
					len : end >> 0;

				// Step 11.
				var final = relativeEnd < 0 ?
					Math.max(len + relativeEnd, 0) :
					Math.min(relativeEnd, len);

				// Step 12.
				while (k < final) {
					O[k] = value;
					k++;
				}

				// Step 13.
				return O;
			}
		});
	}
	if (typeof Int8Array !== 'undefined' && !Int8Array.prototype.fill) {
		Int8Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Uint8Array !== 'undefined' && !Uint8Array.prototype.fill) {
		Uint8Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Uint8ClampedArray !== 'undefined' && !Uint8ClampedArray.prototype.fill) {
		Uint8ClampedArray.prototype.fill = Array.prototype.fill;
	}
	if (typeof Int16Array !== 'undefined' && !Int16Array.prototype.fill) {
		Int16Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Uint16Array !== 'undefined' && !Uint16Array.prototype.fill) {
		Uint16Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Int32Array !== 'undefined' && !Int32Array.prototype.fill) {
		Int32Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Uint32Array !== 'undefined' && !Uint32Array.prototype.fill) {
		Uint32Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Float32Array !== 'undefined' && !Float32Array.prototype.fill) {
		Float32Array.prototype.fill = Array.prototype.fill;
	}
	if (typeof Float64Array !== 'undefined' && !Float64Array.prototype.fill) {
		Float64Array.prototype.fill = Array.prototype.fill;
	}

	//------------------------------------------------------------export---------------------------------------------------
	window['AscCommon'] = window['AscCommon'] || {};
	window["AscCommon"].getSockJs = getSockJs;
	window["AscCommon"].getJSZipUtils = getJSZipUtils;
	window["AscCommon"].getJSZip = getJSZip;
	window["AscCommon"].getBaseUrl = getBaseUrl;
	window["AscCommon"].getEncodingParams = getEncodingParams;
	window["AscCommon"].getEncodingByBOM = getEncodingByBOM;
	window["AscCommon"].saveWithParts = saveWithParts;
	window["AscCommon"].loadFileContent = loadFileContent;
	window["AscCommon"].getImageFromChanges = getImageFromChanges;
	window["AscCommon"].openFileCommand = openFileCommand;
	window["AscCommon"].sendCommand = sendCommand;
	window["AscCommon"].sendSaveFile = sendSaveFile;
	window["AscCommon"].mapAscServerErrorToAscError = mapAscServerErrorToAscError;
	window["AscCommon"].joinUrls = joinUrls;
	window["AscCommon"].getFullImageSrc2 = getFullImageSrc2;
	window["AscCommon"].fSortAscending = fSortAscending;
	window["AscCommon"].fSortDescending = fSortDescending;
	window["AscCommon"].isLeadingSurrogateChar = isLeadingSurrogateChar;
	window["AscCommon"].decodeSurrogateChar = decodeSurrogateChar;
	window["AscCommon"].encodeSurrogateChar = encodeSurrogateChar;
	window["AscCommon"].convertUnicodeToUTF16 = convertUnicodeToUTF16;
	window["AscCommon"].convertUTF16toUnicode = convertUTF16toUnicode;
	window["AscCommon"].build_local_rx = build_local_rx;
	window["AscCommon"].GetFileName = GetFileName;
	window["AscCommon"].GetFileExtension = GetFileExtension;
	window["AscCommon"].changeFileExtention = changeFileExtention;
	window["AscCommon"].getExtentionByFormat = getExtentionByFormat;
	window["AscCommon"].InitOnMessage = InitOnMessage;
	window["AscCommon"].ShowImageFileDialog = ShowImageFileDialog;
	window["AscCommon"].InitDragAndDrop = InitDragAndDrop;
	window["AscCommon"].UploadImageFiles = UploadImageFiles;
    window["AscCommon"].UploadImageUrls = UploadImageUrls;
	window["AscCommon"].CanDropFiles = CanDropFiles;
	window["AscCommon"].getUrlType = getUrlType;
	window["AscCommon"].prepareUrl = prepareUrl;
	window["AscCommon"].getUserColorById = getUserColorById;
	window["AscCommon"].isNullOrEmptyString = isNullOrEmptyString;
	window["AscCommon"].unleakString = unleakString;
	window["AscCommon"].initStreamFromResponse = initStreamFromResponse;

	window["AscCommon"].DocumentUrls = DocumentUrls;
	window["AscCommon"].CLock = CLock;
	window["AscCommon"].CContentChanges = CContentChanges;
	window["AscCommon"].CContentChangesElement = CContentChangesElement;

	window["AscCommon"].CorrectMMToTwips = CorrectMMToTwips;
	window["AscCommon"].TwipsToMM = TwipsToMM;
	window["AscCommon"].MMToTwips = MMToTwips;
	window["AscCommon"].RomanToInt = RomanToInt;
	window["AscCommon"].LatinNumberingToInt = LatinNumberingToInt;

	window["AscCommon"].loadSdk = loadSdk;
	window["AscCommon"].getAltGr = getAltGr;
	window["AscCommon"].getColorThemeByIndex = getColorThemeByIndex;
	window["AscCommon"].isEastAsianScript = isEastAsianScript;

	window["AscCommon"].JSZipWrapper = JSZipWrapper;
	window["AscCommon"].g_oDocumentUrls = g_oDocumentUrls;
	window["AscCommon"].FormulaTablePartInfo = FormulaTablePartInfo;
	window["AscCommon"].cBoolLocal = cBoolLocal;
	window["AscCommon"].cErrorOrigin = cErrorOrigin;
	window["AscCommon"].cErrorLocal = cErrorLocal;
	window["AscCommon"].FormulaSeparators = FormulaSeparators;
	window["AscCommon"].rx_space_g = rx_space_g;
	window["AscCommon"].rx_space = rx_space;
	window["AscCommon"].rx_defName = rx_defName;

	window["AscCommon"].kCurFormatPainterWord = kCurFormatPainterWord;
	window["AscCommon"].parserHelp = parserHelp;
	window["AscCommon"].g_oIdCounter = g_oIdCounter;

	window["AscCommon"].g_oHtmlCursor = g_oHtmlCursor;

	window["AscCommon"].CSignatureDrawer = window["AscCommon"]["CSignatureDrawer"] = CSignatureDrawer;
	var prot = CSignatureDrawer.prototype;
	prot["getImages"] 	= prot.getImages;
	prot["setText"] 	= prot.setText;
	prot["selectImage"] = prot.selectImage;
	prot["isValid"] 	= prot.isValid;
	prot["destroy"] 	= prot.destroy;

	window["AscCommon"].translateManager = new CTranslateManager();
})(window);

window["asc_initAdvancedOptions"] = function(_code, _file_hash, _docInfo)
{
    if (window.isNativeOpenPassword)
	{
		return window["NativeFileOpen_error"](window.isNativeOpenPassword, _file_hash, _docInfo);
	}

    var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;

    if (_code == 90 || _code == 91)
    {
    	if (window["AscDesktopEditor"] && (0 !== window["AscDesktopEditor"]["CryptoMode"]) && !_editor.isLoadFullApi)
		{
            // ждем инициализации
            _editor.asc_initAdvancedOptions_params = [];
            _editor.asc_initAdvancedOptions_params.push(_code);
            _editor.asc_initAdvancedOptions_params.push(_file_hash);
            _editor.asc_initAdvancedOptions_params.push(_docInfo);
            return;
        }

    	if (AscCommon.EncryptionWorker.isNeedCrypt() && !window.checkPasswordFromPlugin)
    	{
            window.checkPasswordFromPlugin = true;
            window.g_asc_plugins.sendToEncryption({ "type": "getPasswordByFile", "hash": _file_hash, "docinfo": _docInfo });
            return;
        }
    }

    window.checkPasswordFromPlugin = false;
    _editor._onNeedParams(undefined, (_code == 90 || _code == 91) ? true : undefined);
};
window.openFileCryptCallback = function(_binary)
{
    var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;

    if (!_editor.isLoadFullApi)
	{
		_editor.openFileCryptBinary = _binary;
		return;
	}

    if (_binary == null)
    {
        _editor.sendEvent("asc_onError", c_oAscError.ID.ConvertationOpenError, c_oAscError.Level.Critical);
        return;
    }

    if ("DOCY" == AscCommon.c_oSerFormat.Signature)
	{
		var isEditor = true;
        if (_binary.length > 4)
		{
			var _signature = (String.fromCharCode(_binary[0]) + String.fromCharCode(_binary[1]) + String.fromCharCode(_binary[2]) + String.fromCharCode(_binary[3]));
			if (_signature != AscCommon.c_oSerFormat.Signature)
				isEditor = false;
		}

        if (!isEditor)
            _editor.OpenDocument("", _binary);
        else
            _editor.OpenDocument2("", _binary);
	}
	else if ("PPTY" == AscCommon.c_oSerFormat.Signature)
	{
        _editor.OpenDocument2("", _binary);
	}
	else
	{
        _editor.openDocument(_binary);
	}

    _editor.sendEvent("asc_onDocumentPassword", ("" != _editor.currentPassword) ? true : false);
};

window["asc_IsNeedBuildCryptedFile"] = function()
{
    if (!window["AscDesktopEditor"])
        return false;

    var _api = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
    var _returnValue = false;

    var _users = null;
    if (_api.CoAuthoringApi && _api.CoAuthoringApi._CoAuthoringApi && _api.CoAuthoringApi._CoAuthoringApi._participants)
        _users = _api.CoAuthoringApi._CoAuthoringApi._participants;

    var _usersCount = 0;
    for (var _user in _users)
    	_usersCount++;

    var isOne = (1 >= _usersCount) ? true : false;

    if (!isOne)
    {
    	//console.log("asc_IsNeedBuildCryptedFile: no one");
    	_returnValue = false;
    }
    else if (null != AscCommon.History.SavedIndex && -1 != AscCommon.History.SavedIndex)
    {
        //console.log("asc_IsNeedBuildCryptedFile: one1");
        _returnValue = true;
    }
    else
    {
        //console.log("asc_IsNeedBuildCryptedFile: one2");
        if (_api.editorId == AscCommon.c_oEditorId.Spreadsheet)
        {
            if (AscCommon.EncryptionWorker.isExistDecryptedChanges)
                _returnValue = true;
        }
        else
        {
            if (0 != AscCommon.CollaborativeEditing.m_aAllChanges.length)
                _returnValue = true;
        }
    }

    window["AscDesktopEditor"]["execCommand"]("encrypt:isneedbuild", "" + _returnValue);
    return _returnValue;
};

window["UpdateSystemPlugins"] = function()
{
    var _plugins = JSON.parse(window["AscDesktopEditor"]["GetInstallPlugins"]());
    _plugins[0]["url"] = _plugins[0]["url"].replace(" ", "%20");
    _plugins[1]["url"] = _plugins[1]["url"].replace(" ", "%20");

    for (var k = 0; k < 2; k++)
    {
        var _pluginsCur = _plugins[k];

        var _len = _pluginsCur["pluginsData"].length;
        for (var i = 0; i < _len; i++)
		{
			_pluginsCur["pluginsData"][i]["baseUrl"] = _pluginsCur["url"] + _pluginsCur["pluginsData"][i]["guid"].substring(4) + "/";

			if (!window["AscDesktopEditor"]["IsLocalFile"]())
			{
                _pluginsCur["pluginsData"][i]["baseUrl"] = "ascdesktop://plugin_content/" + _pluginsCur["pluginsData"][i]["baseUrl"];
            }
        }
    }

    var _array = [];

    for (var k = 0; k < 2; k++)
    {
        var _pluginsCur = _plugins[k];
        var _len = _pluginsCur["pluginsData"].length;

        for (var i = 0; i < _len; i++)
        {
            var _plugin = _pluginsCur["pluginsData"][i];
            for (var j = 0; j < _plugin["variations"].length; j++)
            {
                var _variation = _plugin["variations"][j];
                if (_variation["initDataType"] == "desktop")
                {
                    if (_variation["initData"] == "encryption")
                    {
                    	var _mode = _variation["cryptoMode"];
                    	if (!_mode)
                    		_mode = "1";
                    	AscCommon.EncryptionWorker.cryptoMode = parseInt(_mode);

                        _array.push(_plugin);
                        break;
                    }

                    _array.push(_plugin);
                    break;
                }
            }
        }
    }

    var _arraySystem = [];
    for (var i = 0; i < _array.length; i++)
    {
        var plugin = new Asc.CPlugin();
        plugin["deserialize"](_array[i]);

        _arraySystem.push(plugin);
    }

    window.g_asc_plugins.registerSystem("", _arraySystem);
    window.g_asc_plugins.runAllSystem();
};

window["buildCryptoFile_Start"] = function()
{
    var _editor = window.Asc.editor ? window.Asc.editor : window.editor;
    _editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.Save);

    window.g_asc_plugins.sendToEncryption({ "type" : "generatePassword" });
};

window["buildCryptoFile_End"] = function(url, error, hash, password)
{
    var _editor = window.Asc.editor ? window.Asc.editor : window.editor;
    _editor.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.Save);

    if (0 != error)
	{
		_editor.sendEvent("asc_onError", Asc.c_oAscError.ID.ConvertationSaveError, Asc.c_oAscError.Level.NoCritical);
		return;
    }

    // send password
    _editor._callbackPluginEndAction = function()
	{
		this._callbackPluginEndAction = null;

        _editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.Save);

		// file upload
		var xhr = new XMLHttpRequest();
		xhr.open('GET', "ascdesktop://fonts/" + url, true);
		xhr.responseType = 'arraybuffer';

		if (xhr.overrideMimeType)
			xhr.overrideMimeType('text/plain; charset=x-user-defined');
		else
			xhr.setRequestHeader('Accept-Charset', 'x-user-defined');

		xhr.onload = function()
		{
			if (this.status != 200)
			{
				// error
				return;
			}

			var fileData = new Uint8Array(this.response);

			var ext = ".docx";
			switch (_editor.editorId)
			{
				case AscCommon.c_oEditorId.Presentation:
					ext = ".pptx";
					break;
				case AscCommon.c_oEditorId.Spreadsheet:
					ext = ".xlsx";
					break;
				default:
					break;
			}

			AscCommon.sendSaveFile(_editor.documentId, _editor.documentUserId, "output" + ext, _editor.asc_getSessionToken(), fileData, function(err) {

                _editor.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.Save);
                _editor.sendEvent("asc_onError", Asc.c_oAscError.ID.ConvertationOpenError, Asc.c_oAscError.Level.Critical);

                window["AscDesktopEditor"]["buildCryptedEnd"](false);

			}, function(httpRequest) {
				//console.log(httpRequest.responseText);
				try
				{
					var data = {
						"accounts": httpRequest.responseText ? JSON.parse(httpRequest.responseText) : undefined,
						"hash": hash,
						"password" : password,
						"type": "share"
					};

					window["AscDesktopEditor"]["sendSystemMessage"](data);
					window["AscDesktopEditor"]["CallInAllWindows"]("function(){ if (window.DesktopUpdateFile) { window.DesktopUpdateFile(undefined); } }");

                    _editor.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.Save);

					setTimeout(function() {

                        window["AscDesktopEditor"]["buildCryptedEnd"](true);

					}, 1000);
				}
				catch (err)
				{
				}
			});
		};

		xhr.send(null);
	};
    window.g_asc_plugins.sendToEncryption({"type": "setPasswordByFile", "hash": hash, "password": password});
};

window["NativeFileOpen_error"] = function(error, _file_hash, _docInfo)
{
    var _api = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;

    if ("password" == error)
    {
        window.isNativeOpenPassword = error;

        if (window["AscDesktopEditor"] && (0 !== window["AscDesktopEditor"]["CryptoMode"]) && !_api.isLoadFullApi)
        {
            // ждем инициализации
            _api.asc_initAdvancedOptions_params = [];
            _api.asc_initAdvancedOptions_params.push(90);
            _api.asc_initAdvancedOptions_params.push(_file_hash);
            _api.asc_initAdvancedOptions_params.push(_docInfo);
            return;
        }

        if (AscCommon.EncryptionWorker.isNeedCrypt() && !window.checkPasswordFromPlugin)
        {
            window.checkPasswordFromPlugin = true;
            window.g_asc_plugins.sendToEncryption({ "type": "getPasswordByFile", "hash": _file_hash, "docinfo": _docInfo });
            return;
        }

        window.checkPasswordFromPlugin = false;
        _api._onNeedParams(undefined, true);
    }
    else if ("error" == error)
    {
        _api.sendEvent("asc_onError", c_oAscError.ID.ConvertationOpenError, c_oAscError.Level.Critical);
        return;
    }
};

window["CryptoDownloadAsEnd"] = function()
{
    var _editor = window.Asc.editor ? window.Asc.editor : window.editor;
    _editor.sync_EndAction(Asc.c_oAscAsyncActionType.BlockInteraction, Asc.c_oAscAsyncAction.DownloadAs);

    window.isCloudCryptoDownloadAs = undefined;
};

window["AscDesktopEditor_Save"] = function()
{
    var _editor = window.Asc.editor ? window.Asc.editor : window.editor;
    if (!_editor.asc_Save(false))
    {
    	// сейва не будет. сами посылаем callback
        window["AscDesktopEditor"]["OnSave"]();
    }
};
/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

/**
 * User: Ilja.Kirillov
 * Date: 27.10.2016
 * Time: 12:11
 */

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function(window, undefined)
{
	function GetHistoryPointStringDescription(nDescription)
	{
		var sString = "Unknown";
		switch (nDescription)
		{
			case AscDFH.historydescription_Cut                                         :
				sString = "Cut";
				break;
			case AscDFH.historydescription_PasteButtonIE                               :
				sString = "PasteButtonIE";
				break;
			case AscDFH.historydescription_PasteButtonNotIE                            :
				sString = "PasteButtonNotIE";
				break;
			case AscDFH.historydescription_ChartDrawingObjects                         :
				sString = "ChartDrawingObjects";
				break;
			case AscDFH.historydescription_CommonControllerCheckChartText              :
				sString = "CommonControllerCheckChartText";
				break;
			case AscDFH.historydescription_CommonControllerUnGroup                     :
				sString = "CommonControllerUnGroup";
				break;
			case AscDFH.historydescription_CommonControllerCheckSelected               :
				sString = "CommonControllerCheckSelected";
				break;
			case AscDFH.historydescription_CommonControllerSetGraphicObject            :
				sString = "CommonControllerSetGraphicObject";
				break;
			case AscDFH.historydescription_CommonStatesAddNewShape                     :
				sString = "CommonStatesAddNewShape";
				break;
			case AscDFH.historydescription_CommonStatesRotate                          :
				sString = "CommonStatesRotate";
				break;
			case AscDFH.historydescription_PasteNative                                 :
				sString = "PasteNative";
				break;
			case AscDFH.historydescription_Document_GroupUnGroup                       :
				sString = "Document_GroupUnGroup";
				break;
			case AscDFH.historydescription_Document_SetDefaultLanguage                 :
				sString = "Document_SetDefaultLanguage";
				break;
			case AscDFH.historydescription_Document_ChangeColorScheme                  :
				sString = "Document_ChangeColorScheme";
				break;
			case AscDFH.historydescription_Document_AddChart                           :
				sString = "Document_AddChart";
				break;
			case AscDFH.historydescription_Document_EditChart                          :
				sString = "Document_EditChart";
				break;
			case AscDFH.historydescription_Document_DragText                           :
				sString = "Document_DragText";
				break;
			case AscDFH.historydescription_Document_DocumentContentExtendToPos         :
				sString = "Document_DocumentContentExtendToPos";
				break;
			case AscDFH.historydescription_Document_AddHeader                          :
				sString = "Document_AddHeader";
				break;
			case AscDFH.historydescription_Document_AddFooter                          :
				sString = "Document_AddFooter";
				break;
			case AscDFH.historydescription_Document_ParagraphExtendToPos               :
				sString = "Document_ParagraphExtendToPos";
				break;
			case AscDFH.historydescription_Document_ParagraphChangeFrame               :
				sString = "Document_ParagraphChangeFrame";
				break;
			case AscDFH.historydescription_Document_ReplaceAll                         :
				sString = "Document_ReplaceAll";
				break;
			case AscDFH.historydescription_Document_ReplaceSingle                      :
				sString = "Document_ReplaceSingle";
				break;
			case AscDFH.historydescription_Document_TableAddNewRowByTab                :
				sString = "Document_TableAddNewRowByTab";
				break;
			case AscDFH.historydescription_Document_AddNewShape                        :
				sString = "Document_AddNewShape";
				break;
			case AscDFH.historydescription_Document_EditWrapPolygon                    :
				sString = "Document_EditWrapPolygon";
				break;
			case AscDFH.historydescription_Document_MoveInlineObject                   :
				sString = "Document_MoveInlineObject";
				break;
			case AscDFH.historydescription_Document_CopyAndMoveInlineObject            :
				sString = "Document_CopyAndMoveInlineObject";
				break;
			case AscDFH.historydescription_Document_RotateInlineDrawing                :
				sString = "Document_RotateInlineDrawing";
				break;
			case AscDFH.historydescription_Document_RotateFlowDrawingCtrl              :
				sString = "Document_RotateFlowDrawingCtrl";
				break;
			case AscDFH.historydescription_Document_RotateFlowDrawingNoCtrl            :
				sString = "Document_RotateFlowDrawingNoCtrl";
				break;
			case AscDFH.historydescription_Document_MoveInGroup                        :
				sString = "Document_MoveInGroup";
				break;
			case AscDFH.historydescription_Document_ChangeWrapContour                  :
				sString = "Document_ChangeWrapContour";
				break;
			case AscDFH.historydescription_Document_ChangeWrapContourAddPoint          :
				sString = "Document_ChangeWrapContourAddPoint";
				break;
			case AscDFH.historydescription_Document_GrObjectsBringToFront              :
				sString = "Document_GrObjectsBringToFront";
				break;
			case AscDFH.historydescription_Document_GrObjectsBringForwardGroup         :
				sString = "Document_GrObjectsBringForwardGroup";
				break;
			case AscDFH.historydescription_Document_GrObjectsBringForward              :
				sString = "Document_GrObjectsBringForward";
				break;
			case AscDFH.historydescription_Document_GrObjectsSendToBackGroup           :
				sString = "Document_GrObjectsSendToBackGroup";
				break;
			case AscDFH.historydescription_Document_GrObjectsSendToBack                :
				sString = "Document_GrObjectsSendToBack";
				break;
			case AscDFH.historydescription_Document_GrObjectsBringBackwardGroup        :
				sString = "Document_GrObjectsBringBackwardGroup";
				break;
			case AscDFH.historydescription_Document_GrObjectsBringBackward             :
				sString = "Document_GrObjectsBringBackward";
				break;
			case AscDFH.historydescription_Document_GrObjectsChangeWrapPolygon         :
				sString = "Document_GrObjectsChangeWrapPolygon";
				break;
			case AscDFH.historydescription_Document_MathAutoCorrect                    :
				sString = "Document_MathAutoCorrect";
				break;
			case AscDFH.historydescription_Document_SetFramePrWithFontFamily           :
				sString = "Document_SetFramePrWithFontFamily";
				break;
			case AscDFH.historydescription_Document_SetFramePr                         :
				sString = "Document_SetFramePr";
				break;
			case AscDFH.historydescription_Document_SetFramePrWithFontFamilyLong       :
				sString = "Document_SetFramePrWithFontFamilyLong";
				break;
			case AscDFH.historydescription_Document_SetTextFontName                    :
				sString = "Document_SetTextFontName";
				break;
			case AscDFH.historydescription_Document_SetTextFontSize                    :
				sString = "Document_SetTextFontSize";
				break;
			case AscDFH.historydescription_Document_SetTextBold                        :
				sString = "Document_SetTextBold";
				break;
			case AscDFH.historydescription_Document_SetTextItalic                      :
				sString = "Document_SetTextItalic";
				break;
			case AscDFH.historydescription_Document_SetTextUnderline                   :
				sString = "Document_SetTextUnderline";
				break;
			case AscDFH.historydescription_Document_SetTextStrikeout                   :
				sString = "Document_SetTextStrikeout";
				break;
			case AscDFH.historydescription_Document_SetTextDStrikeout                  :
				sString = "Document_SetTextDStrikeout";
				break;
			case AscDFH.historydescription_Document_SetTextSpacing                     :
				sString = "Document_SetTextSpacing";
				break;
			case AscDFH.historydescription_Document_SetTextCaps                        :
				sString = "Document_SetTextCaps";
				break;
			case AscDFH.historydescription_Document_SetTextSmallCaps                   :
				sString = "Document_SetTextSmallCaps";
				break;
			case AscDFH.historydescription_Document_SetTextPosition                    :
				sString = "Document_SetTextPosition";
				break;
			case AscDFH.historydescription_Document_SetTextLang                        :
				sString = "Document_SetTextLang";
				break;
			case AscDFH.historydescription_Document_SetParagraphLineSpacing            :
				sString = "Document_SetParagraphLineSpacing";
				break;
			case AscDFH.historydescription_Document_SetParagraphLineSpacingBeforeAfter :
				sString = "Document_SetParagraphLineSpacingBeforeAfter";
				break;
			case AscDFH.historydescription_Document_IncFontSize                        :
				sString = "Document_IncFontSize";
				break;
			case AscDFH.historydescription_Document_DecFontSize                        :
				sString = "Document_DecFontSize";
				break;
			case AscDFH.historydescription_Document_SetParagraphBorders                :
				sString = "Document_SetParagraphBorders";
				break;
			case AscDFH.historydescription_Document_SetParagraphPr                     :
				sString = "Document_SetParagraphPr";
				break;
			case AscDFH.historydescription_Document_SetParagraphAlign                  :
				sString = "Document_SetParagraphAlign";
				break;
			case AscDFH.historydescription_Document_SetTextVertAlign                   :
				sString = "Document_SetTextVertAlign";
				break;
			case AscDFH.historydescription_Document_SetParagraphNumbering              :
				sString = "Document_SetParagraphNumbering";
				break;
			case AscDFH.historydescription_Document_SetParagraphStyle                  :
				sString = "Document_SetParagraphStyle";
				break;
			case AscDFH.historydescription_Document_SetParagraphPageBreakBefore        :
				sString = "Document_SetParagraphPageBreakBefore";
				break;
			case AscDFH.historydescription_Document_SetParagraphWidowControl           :
				sString = "Document_SetParagraphWidowControl";
				break;
			case AscDFH.historydescription_Document_SetParagraphKeepLines              :
				sString = "Document_SetParagraphKeepLines";
				break;
			case AscDFH.historydescription_Document_SetParagraphKeepNext               :
				sString = "Document_SetParagraphKeepNext";
				break;
			case AscDFH.historydescription_Document_SetParagraphContextualSpacing      :
				sString = "Document_SetParagraphContextualSpacing";
				break;
			case AscDFH.historydescription_Document_SetTextHighlightNone               :
				sString = "Document_SetTextHighlightNone";
				break;
			case AscDFH.historydescription_Document_SetTextHighlightColor              :
				sString = "Document_SetTextHighlightColor";
				break;
			case AscDFH.historydescription_Document_SetTextColor                       :
				sString = "Document_SetTextColor";
				break;
			case AscDFH.historydescription_Document_SetParagraphShd                    :
				sString = "Document_SetParagraphShd";
				break;
			case AscDFH.historydescription_Document_SetParagraphIndent                 :
				sString = "Document_SetParagraphIndent";
				break;
			case AscDFH.historydescription_Document_IncParagraphIndent                 :
				sString = "Document_IncParagraphIndent";
				break;
			case AscDFH.historydescription_Document_DecParagraphIndent                 :
				sString = "Document_DecParagraphIndent";
				break;
			case AscDFH.historydescription_Document_SetParagraphIndentRight            :
				sString = "Document_SetParagraphIndentRight";
				break;
			case AscDFH.historydescription_Document_SetParagraphIndentFirstLine        :
				sString = "Document_SetParagraphIndentFirstLine";
				break;
			case AscDFH.historydescription_Document_SetPageOrientation                 :
				sString = "Document_SetPageOrientation";
				break;
			case AscDFH.historydescription_Document_SetPageSize                        :
				sString = "Document_SetPageSize";
				break;
			case AscDFH.historydescription_Document_AddPageBreak                       :
				sString = "Document_AddPageBreak";
				break;
			case AscDFH.historydescription_Document_AddPageNumToHdrFtr                 :
				sString = "Document_AddPageNumToHdrFtr";
				break;
			case AscDFH.historydescription_Document_AddPageNumToCurrentPos             :
				sString = "Document_AddPageNumToCurrentPos";
				break;
			case AscDFH.historydescription_Document_SetHdrFtrDistance                  :
				sString = "Document_SetHdrFtrDistance";
				break;
			case AscDFH.historydescription_Document_SetHdrFtrFirstPage                 :
				sString = "Document_SetHdrFtrFirstPage";
				break;
			case AscDFH.historydescription_Document_SetHdrFtrEvenAndOdd                :
				sString = "Document_SetHdrFtrEvenAndOdd";
				break;
			case AscDFH.historydescription_Document_SetHdrFtrLink                      :
				sString = "Document_SetHdrFtrLink";
				break;
			case AscDFH.historydescription_Document_AddTable                           :
				sString = "Document_AddTable";
				break;
			case AscDFH.historydescription_Document_TableAddRowAbove                   :
				sString = "Document_TableAddRowAbove";
				break;
			case AscDFH.historydescription_Document_TableAddRowBelow                   :
				sString = "Document_TableAddRowBelow";
				break;
			case AscDFH.historydescription_Document_TableAddColumnLeft                 :
				sString = "Document_TableAddColumnLeft";
				break;
			case AscDFH.historydescription_Document_TableAddColumnRight                :
				sString = "Document_TableAddColumnRight";
				break;
			case AscDFH.historydescription_Document_TableRemoveRow                     :
				sString = "Document_TableRemoveRow";
				break;
			case AscDFH.historydescription_Document_TableRemoveColumn                  :
				sString = "Document_TableRemoveColumn";
				break;
			case AscDFH.historydescription_Document_RemoveTable                        :
				sString = "Document_RemoveTable";
				break;
			case AscDFH.historydescription_Document_MergeTableCells                    :
				sString = "Document_MergeTableCells";
				break;
			case AscDFH.historydescription_Document_SplitTableCells                    :
				sString = "Document_SplitTableCells";
				break;
			case AscDFH.historydescription_Document_ApplyTablePr                       :
				sString = "Document_ApplyTablePr";
				break;
			case AscDFH.historydescription_Document_AddImageUrl                        :
				sString = "Document_AddImageUrl";
				break;
			case AscDFH.historydescription_Document_AddImageUrlLong                    :
				sString = "Document_AddImageUrlLong";
				break;
			case AscDFH.historydescription_Document_AddImageToPage                     :
				sString = "Document_AddImageToPage";
				break;
			case AscDFH.historydescription_Document_ApplyImagePrWithUrl                :
				sString = "Document_ApplyImagePrWithUrl";
				break;
			case AscDFH.historydescription_Document_ApplyImagePrWithUrlLong            :
				sString = "Document_ApplyImagePrWithUrlLong";
				break;
			case AscDFH.historydescription_Document_ApplyImagePrWithFillUrl            :
				sString = "Document_ApplyImagePrWithFillUrl";
				break;
			case AscDFH.historydescription_Document_ApplyImagePrWithFillUrlLong        :
				sString = "Document_ApplyImagePrWithFillUrlLong";
				break;
			case AscDFH.historydescription_Document_ApplyImagePr                       :
				sString = "Document_ApplyImagePr";
				break;
			case AscDFH.historydescription_Document_AddHyperlink                       :
				sString = "Document_AddHyperlink";
				break;
			case AscDFH.historydescription_Document_ChangeHyperlink                    :
				sString = "Document_ChangeHyperlink";
				break;
			case AscDFH.historydescription_Document_RemoveHyperlink                    :
				sString = "Document_RemoveHyperlink";
				break;
			case AscDFH.historydescription_Document_ReplaceMisspelledWord              :
				sString = "Document_ReplaceMisspelledWord";
				break;
			case AscDFH.historydescription_Document_AddComment                         :
				sString = "Document_AddComment";
				break;
			case AscDFH.historydescription_Document_RemoveComment                      :
				sString = "Document_RemoveComment";
				break;
			case AscDFH.historydescription_Document_ChangeComment                      :
				sString = "Document_ChangeComment";
				break;
			case AscDFH.historydescription_Document_SetTextFontNameLong                :
				sString = "Document_SetTextFontNameLong";
				break;
			case AscDFH.historydescription_Document_AddImage                           :
				sString = "Document_AddImage";
				break;
			case AscDFH.historydescription_Document_ClearFormatting                    :
				sString = "Document_ClearFormatting";
				break;
			case AscDFH.historydescription_Document_AddSectionBreak                    :
				sString = "Document_AddSectionBreak";
				break;
			case AscDFH.historydescription_Document_AddMath                            :
				sString = "Document_AddMath";
				break;
			case AscDFH.historydescription_Document_SetParagraphTabs                   :
				sString = "Document_SetParagraphTabs";
				break;
			case AscDFH.historydescription_Document_SetParagraphIndentFromRulers       :
				sString = "Document_SetParagraphIndentFromRulers";
				break;
			case AscDFH.historydescription_Document_SetDocumentMargin_Hor              :
				sString = "Document_SetDocumentMargin_Hor";
				break;
			case AscDFH.historydescription_Document_SetTableMarkup_Hor                 :
				sString = "Document_SetTableMarkup_Hor";
				break;
			case AscDFH.historydescription_Document_SetDocumentMargin_Ver              :
				sString = "Document_SetDocumentMargin_Ver";
				break;
			case AscDFH.historydescription_Document_SetHdrFtrBounds                    :
				sString = "Document_SetHdrFtrBounds";
				break;
			case AscDFH.historydescription_Document_SetTableMarkup_Ver                 :
				sString = "Document_SetTableMarkup_Ver";
				break;
			case AscDFH.historydescription_Document_DocumentExtendToPos                :
				sString = "Document_DocumentExtendToPos";
				break;
			case AscDFH.historydescription_Document_AddDropCap                         :
				sString = "Document_AddDropCap";
				break;
			case AscDFH.historydescription_Document_RemoveDropCap                      :
				sString = "Document_RemoveDropCap";
				break;
			case AscDFH.historydescription_Document_SetTextHighlight                   :
				sString = "Document_SetTextHighlight";
				break;
			case AscDFH.historydescription_Document_BackSpaceButton                    :
				sString = "Document_BackSpaceButton";
				break;
			case AscDFH.historydescription_Document_MoveParagraphByTab                 :
				sString = "Document_MoveParagraphByTab";
				break;
			case AscDFH.historydescription_Document_AddTab                             :
				sString = "Document_AddTab";
				break;
			case AscDFH.historydescription_Document_EnterButton                        :
				sString = "Document_EnterButton";
				break;
			case AscDFH.historydescription_Document_SpaceButton                        :
				sString = "Document_SpaceButton";
				break;
			case AscDFH.historydescription_Document_ShiftInsert                        :
				sString = "Document_ShiftInsert";
				break;
			case AscDFH.historydescription_Document_ShiftInsertSafari                  :
				sString = "Document_ShiftInsertSafari";
				break;
			case AscDFH.historydescription_Document_DeleteButton                       :
				sString = "Document_DeleteButton";
				break;
			case AscDFH.historydescription_Document_ShiftDeleteButton                  :
				sString = "Document_ShiftDeleteButton";
				break;
			case AscDFH.historydescription_Document_SetStyleHeading1                   :
				sString = "Document_SetStyleHeading1";
				break;
			case AscDFH.historydescription_Document_SetStyleHeading2                   :
				sString = "Document_SetStyleHeading2";
				break;
			case AscDFH.historydescription_Document_SetStyleHeading3                   :
				sString = "Document_SetStyleHeading3";
				break;
			case AscDFH.historydescription_Document_SetTextStrikeoutHotKey             :
				sString = "Document_SetTextStrikeoutHotKey";
				break;
			case AscDFH.historydescription_Document_SetTextBoldHotKey                  :
				sString = "Document_SetTextBoldHotKey";
				break;
			case AscDFH.historydescription_Document_SetParagraphAlignHotKey            :
				sString = "Document_SetParagraphAlignHotKey";
				break;
			case AscDFH.historydescription_Document_AddEuroLetter                      :
				sString = "Document_AddEuroLetter";
				break;
			case AscDFH.historydescription_Document_SetTextItalicHotKey                :
				sString = "Document_SetTextItalicHotKey";
				break;
			case AscDFH.historydescription_Document_SetParagraphAlignHotKey2           :
				sString = "Document_SetParagraphAlignHotKey2";
				break;
			case AscDFH.historydescription_Document_SetParagraphNumberingHotKey        :
				sString = "Document_SetParagraphNumberingHotKey";
				break;
			case AscDFH.historydescription_Document_SetParagraphAlignHotKey3           :
				sString = "Document_SetParagraphAlignHotKey3";
				break;
			case AscDFH.historydescription_Document_AddPageNumHotKey                   :
				sString = "Document_AddPageNumHotKey";
				break;
			case AscDFH.historydescription_Document_SetParagraphAlignHotKey4           :
				sString = "Document_SetParagraphAlignHotKey4";
				break;
			case AscDFH.historydescription_Document_SetTextUnderlineHotKey             :
				sString = "Document_SetTextUnderlineHotKey";
				break;
			case AscDFH.historydescription_Document_FormatPasteHotKey                  :
				sString = "Document_FormatPasteHotKey";
				break;
			case AscDFH.historydescription_Document_PasteHotKey                        :
				sString = "Document_PasteHotKey";
				break;
			case AscDFH.historydescription_Document_PasteSafariHotKey                  :
				sString = "Document_PasteSafariHotKey";
				break;
			case AscDFH.historydescription_Document_CutHotKey                          :
				sString = "Document_CutHotKey";
				break;
			case AscDFH.historydescription_Document_SetTextVertAlignHotKey             :
				sString = "Document_SetTextVertAlignHotKey";
				break;
			case AscDFH.historydescription_Document_AddMathHotKey                      :
				sString = "Document_AddMathHotKey";
				break;
			case AscDFH.historydescription_Document_SetTextVertAlignHotKey2            :
				sString = "Document_SetTextVertAlignHotKey2";
				break;
			case AscDFH.historydescription_Document_MinusButton                        :
				sString = "Document_MinusButton";
				break;
			case AscDFH.historydescription_Document_SetTextVertAlignHotKey3            :
				sString = "Document_SetTextVertAlignHotKey3";
				break;
			case AscDFH.historydescription_Document_AddLetter                          :
				sString = "Document_AddLetter";
				break;
			case AscDFH.historydescription_Document_MoveTableBorder                    :
				sString = "Document_MoveTableBorder";
				break;
			case AscDFH.historydescription_Document_FormatPasteHotKey2                 :
				sString = "Document_FormatPasteHotKey2";
				break;
			case AscDFH.historydescription_Document_SetTextHighlight2                  :
				sString = "Document_SetTextHighlight2";
				break;
			case AscDFH.historydescription_Document_AddTextFromTextBox                 :
				sString = "Document_AddTextFromTextBox";
				break;
			case AscDFH.historydescription_Document_AddMailMergeField                  :
				sString = "Document_AddMailMergeField";
				break;
			case AscDFH.historydescription_Document_MoveInlineTable                    :
				sString = "Document_MoveInlineTable";
				break;
			case AscDFH.historydescription_Document_MoveFlowTable                      :
				sString = "Document_MoveFlowTable";
				break;
			case AscDFH.historydescription_Document_RestoreFieldTemplateText           :
				sString = "Document_RestoreFieldTemplateText";
				break;

			case AscDFH.historydescription_Spreadsheet_SetCellFontName                 :
				sString = "Spreadsheet_SetCellFontName";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellFontSize                 :
				sString = "Spreadsheet_SetCellFontSize";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellBold                     :
				sString = "Spreadsheet_SetCellBold";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellItalic                   :
				sString = "Spreadsheet_SetCellItalic";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellUnderline                :
				sString = "Spreadsheet_SetCellUnderline";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellStrikeout                :
				sString = "Spreadsheet_SetCellStrikeout";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellSubscript                :
				sString = "Spreadsheet_SetCellSubscript";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellSuperscript              :
				sString = "Spreadsheet_SetCellSuperscript";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellAlign                    :
				sString = "Spreadsheet_SetCellAlign";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellVertAlign                :
				sString = "Spreadsheet_SetCellVertAlign";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellTextColor                :
				sString = "Spreadsheet_SetCellTextColor";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellBackgroundColor          :
				sString = "Spreadsheet_SetCellBackgroundColor";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellIncreaseFontSize         :
				sString = "Spreadsheet_SetCellIncreaseFontSize";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellDecreaseFontSize         :
				sString = "Spreadsheet_SetCellDecreaseFontSize";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellHyperlinkAdd             :
				sString = "Spreadsheet_SetCellHyperlinkAdd";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellHyperlinkModify          :
				sString = "Spreadsheet_SetCellHyperlinkModify";
				break;
			case AscDFH.historydescription_Spreadsheet_SetCellHyperlinkRemove          :
				sString = "Spreadsheet_SetCellHyperlinkRemove";
				break;
			case AscDFH.historydescription_Spreadsheet_EditChart                       :
				sString = "Spreadsheet_EditChart";
				break;
			case AscDFH.historydescription_Spreadsheet_Remove                          :
				sString = "Spreadsheet_Remove";
				break;
			case AscDFH.historydescription_Spreadsheet_AddTab                          :
				sString = "Spreadsheet_AddTab";
				break;
			case AscDFH.historydescription_Spreadsheet_AddNewParagraph                 :
				sString = "Spreadsheet_AddNewParagraph";
				break;
			case AscDFH.historydescription_Spreadsheet_AddSpace                        :
				sString = "Spreadsheet_AddSpace";
				break;
			case AscDFH.historydescription_Spreadsheet_AddItem                         :
				sString = "Spreadsheet_AddItem";
				break;
			case AscDFH.historydescription_Spreadsheet_PutPrLineSpacing                :
				sString = "Spreadsheet_PutPrLineSpacing";
				break;
			case AscDFH.historydescription_Spreadsheet_SetParagraphSpacing             :
				sString = "Spreadsheet_SetParagraphSpacing";
				break;
			case AscDFH.historydescription_Spreadsheet_SetGraphicObjectsProps          :
				sString = "Spreadsheet_SetGraphicObjectsProps";
				break;
			case AscDFH.historydescription_Spreadsheet_ParaApply                       :
				sString = "Spreadsheet_ParaApply";
				break;
			case AscDFH.historydescription_Spreadsheet_GraphicObjectLayer              :
				sString = "Spreadsheet_GraphicObjectLayer";
				break;
			case AscDFH.historydescription_Spreadsheet_ParagraphAdd                    :
				sString = "Spreadsheet_ParagraphAdd";
				break;
			case AscDFH.historydescription_Spreadsheet_CreateGroup                     :
				sString = "Spreadsheet_CreateGroup";
				break;
			case AscDFH.historydescription_CommonDrawings_ChangeAdj                    :
				sString = "CommonDrawings_ChangeAdj";
				break;
			case AscDFH.historydescription_CommonDrawings_EndTrack                     :
				sString = "CommonDrawings_EndTrack";
				break;
			case AscDFH.historydescription_CommonDrawings_CopyCtrl                     :
				sString = "CommonDrawings_CopyCtrl";
				break;
			case AscDFH.historydescription_Presentation_ParaApply                      :
				sString = "Presentation_ParaApply";
				break;
			case AscDFH.historydescription_Presentation_ParaFormatPaste                :
				sString = "Presentation_ParaFormatPaste";
				break;
			case AscDFH.historydescription_Presentation_AddNewParagraph                :
				sString = "Presentation_AddNewParagraph";
				break;
			case AscDFH.historydescription_Presentation_CreateGroup                    :
				sString = "Presentation_CreateGroup";
				break;
			case AscDFH.historydescription_Presentation_UnGroup                        :
				sString = "Presentation_UnGroup";
				break;
			case AscDFH.historydescription_Presentation_AddChart                       :
				sString = "Presentation_AddChart";
				break;
			case AscDFH.historydescription_Presentation_EditChart                      :
				sString = "Presentation_EditChart";
				break;
			case AscDFH.historydescription_Presentation_ParagraphAdd                   :
				sString = "Presentation_ParagraphAdd";
				break;
			case AscDFH.historydescription_Presentation_ParagraphClearFormatting       :
				sString = "Presentation_ParagraphClearFormatting";
				break;
			case AscDFH.historydescription_Presentation_SetParagraphAlign              :
				sString = "Presentation_SetParagraphAlign";
				break;
			case AscDFH.historydescription_Presentation_SetParagraphSpacing            :
				sString = "Presentation_SetParagraphSpacing";
				break;
			case AscDFH.historydescription_Presentation_SetParagraphTabs               :
				sString = "Presentation_SetParagraphTabs";
				break;
			case AscDFH.historydescription_Presentation_SetParagraphIndent             :
				sString = "Presentation_SetParagraphIndent";
				break;
			case AscDFH.historydescription_Presentation_SetParagraphNumbering          :
				sString = "Presentation_SetParagraphNumbering";
				break;
			case AscDFH.historydescription_Presentation_ParagraphIncDecFontSize        :
				sString = "Presentation_ParagraphIncDecFontSize";
				break;
			case AscDFH.historydescription_Presentation_ParagraphIncDecIndent          :
				sString = "Presentation_ParagraphIncDecIndent";
				break;
			case AscDFH.historydescription_Presentation_SetImageProps                  :
				sString = "Presentation_SetImageProps";
				break;
			case AscDFH.historydescription_Presentation_SetShapeProps                  :
				sString = "Presentation_SetShapeProps";
				break;
			case AscDFH.historydescription_Presentation_ChartApply                     :
				sString = "Presentation_ChartApply";
				break;
			case AscDFH.historydescription_Presentation_ChangeShapeType                :
				sString = "Presentation_ChangeShapeType";
				break;
			case AscDFH.historydescription_Presentation_SetVerticalAlign               :
				sString = "Presentation_SetVerticalAlign";
				break;
			case AscDFH.historydescription_Presentation_HyperlinkAdd                   :
				sString = "Presentation_HyperlinkAdd";
				break;
			case AscDFH.historydescription_Presentation_HyperlinkModify                :
				sString = "Presentation_HyperlinkModify";
				break;
			case AscDFH.historydescription_Presentation_HyperlinkRemove                :
				sString = "Presentation_HyperlinkRemove";
				break;
			case AscDFH.historydescription_Presentation_DistHor                        :
				sString = "Presentation_DistHor";
				break;
			case AscDFH.historydescription_Presentation_DistVer                        :
				sString = "Presentation_DistVer";
				break;
			case AscDFH.historydescription_Presentation_BringToFront                   :
				sString = "Presentation_BringToFront";
				break;
			case AscDFH.historydescription_Presentation_BringForward                   :
				sString = "Presentation_BringForward";
				break;
			case AscDFH.historydescription_Presentation_SendToBack                     :
				sString = "Presentation_SendToBack";
				break;
			case AscDFH.historydescription_Presentation_BringBackward                  :
				sString = "Presentation_BringBackward";
				break;
			case AscDFH.historydescription_Presentation_ApplyTiming                    :
				sString = "Presentation_ApplyTiming";
				break;
			case AscDFH.historydescription_Presentation_MoveSlidesToEnd                :
				sString = "Presentation_MoveSlidesToEnd";
				break;
			case AscDFH.historydescription_Presentation_MoveSlidesNextPos              :
				sString = "Presentation_MoveSlidesNextPos";
				break;
			case AscDFH.historydescription_Presentation_MoveSlidesPrevPos              :
				sString = "Presentation_MoveSlidesPrevPos";
				break;
			case AscDFH.historydescription_Presentation_MoveSlidesToStart              :
				sString = "Presentation_MoveSlidesToStart";
				break;
			case AscDFH.historydescription_Presentation_MoveComments                   :
				sString = "Presentation_MoveComments";
				break;
			case AscDFH.historydescription_Presentation_TableBorder                    :
				sString = "Presentation_TableBorder";
				break;
			case AscDFH.historydescription_Presentation_AddFlowImage                   :
				sString = "Presentation_AddFlowImage";
				break;
			case AscDFH.historydescription_Presentation_AddFlowTable                   :
				sString = "Presentation_AddFlowTable";
				break;
			case AscDFH.historydescription_Presentation_ChangeBackground               :
				sString = "Presentation_ChangeBackground";
				break;
			case AscDFH.historydescription_Presentation_AddNextSlide                   :
				sString = "Presentation_AddNextSlide";
				break;
			case AscDFH.historydescription_Presentation_ShiftSlides                    :
				sString = "Presentation_ShiftSlides";
				break;
			case AscDFH.historydescription_Presentation_DeleteSlides                   :
				sString = "Presentation_DeleteSlides";
				break;
			case AscDFH.historydescription_Presentation_ChangeLayout                   :
				sString = "Presentation_ChangeLayout";
				break;
			case AscDFH.historydescription_Presentation_ChangeSlideSize                :
				sString = "Presentation_ChangeSlideSize";
				break;
			case AscDFH.historydescription_Presentation_ChangeColorScheme              :
				sString = "Presentation_ChangeColorScheme";
				break;
			case AscDFH.historydescription_Presentation_AddComment                     :
				sString = "Presentation_AddComment";
				break;
			case AscDFH.historydescription_Presentation_ChangeComment                  :
				sString = "Presentation_ChangeComment";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrFontName              :
				sString = "Presentation_PutTextPrFontName";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrFontSize              :
				sString = "Presentation_PutTextPrFontSize";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrBold                  :
				sString = "Presentation_PutTextPrBold";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrItalic                :
				sString = "Presentation_PutTextPrItalic";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrUnderline             :
				sString = "Presentation_PutTextPrUnderline";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrStrikeout             :
				sString = "Presentation_PutTextPrStrikeout";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrLineSpacing           :
				sString = "Presentation_PutTextPrLineSpacing";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrSpacingBeforeAfter    :
				sString = "Presentation_PutTextPrSpacingBeforeAfter";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrIncreaseFontSize      :
				sString = "Presentation_PutTextPrIncreaseFontSize";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrDecreaseFontSize      :
				sString = "Presentation_PutTextPrDecreaseFontSize";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrAlign                 :
				sString = "Presentation_PutTextPrAlign";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrBaseline              :
				sString = "Presentation_PutTextPrBaseline";
				break;
			case AscDFH.historydescription_Presentation_PutTextPrListType              :
				sString = "Presentation_PutTextPrListType";
				break;
			case AscDFH.historydescription_Presentation_PutTextColor                   :
				sString = "Presentation_PutTextColor";
				break;
			case AscDFH.historydescription_Presentation_PutTextColor2                  :
				sString = "Presentation_PutTextColor2";
				break;
			case AscDFH.historydescription_Presentation_PutPrIndent                    :
				sString = "Presentation_PutPrIndent";
				break;
			case AscDFH.historydescription_Presentation_PutPrIndentRight               :
				sString = "Presentation_PutPrIndentRight";
				break;
			case AscDFH.historydescription_Presentation_PutPrFirstLineIndent           :
				sString = "Presentation_PutPrFirstLineIndent";
				break;
			case AscDFH.historydescription_Presentation_AddPageBreak                   :
				sString = "Presentation_AddPageBreak";
				break;
			case AscDFH.historydescription_Presentation_AddRowAbove                    :
				sString = "Presentation_AddRowAbove";
				break;
			case AscDFH.historydescription_Presentation_AddRowBelow                    :
				sString = "Presentation_AddRowBelow";
				break;
			case AscDFH.historydescription_Presentation_AddColLeft                     :
				sString = "Presentation_AddColLeft";
				break;
			case AscDFH.historydescription_Presentation_AddColRight                    :
				sString = "Presentation_AddColRight";
				break;
			case AscDFH.historydescription_Presentation_RemoveRow                      :
				sString = "Presentation_RemoveRow";
				break;
			case AscDFH.historydescription_Presentation_RemoveCol                      :
				sString = "Presentation_RemoveCol";
				break;
			case AscDFH.historydescription_Presentation_RemoveTable                    :
				sString = "Presentation_RemoveTable";
				break;
			case AscDFH.historydescription_Presentation_MergeCells                     :
				sString = "Presentation_MergeCells";
				break;
			case AscDFH.historydescription_Presentation_SplitCells                     :
				sString = "Presentation_SplitCells";
				break;
			case AscDFH.historydescription_Presentation_TblApply                       :
				sString = "Presentation_TblApply";
				break;
			case AscDFH.historydescription_Presentation_RemoveComment                  :
				sString = "Presentation_RemoveComment";
				break;
			case AscDFH.historydescription_Presentation_EndFontLoad                    :
				sString = "Presentation_EndFontLoad";
				break;
			case AscDFH.historydescription_Presentation_ChangeTheme                    :
				sString = "Presentation_ChangeTheme";
				break;
			case AscDFH.historydescription_Presentation_TableMoveFromRulers            :
				sString = "Presentation_TableMoveFromRulers";
				break;
			case AscDFH.historydescription_Presentation_TableMoveFromRulersInline      :
				sString = "Presentation_TableMoveFromRulersInline";
				break;
			case AscDFH.historydescription_Presentation_PasteOnThumbnails              :
				sString = "Presentation_PasteOnThumbnails";
				break;
			case AscDFH.historydescription_Presentation_PasteOnThumbnailsSafari        :
				sString = "Presentation_PasteOnThumbnailsSafari";
				break;
			case AscDFH.historydescription_Document_ConvertOldEquation                 :
				sString = "Document_ConvertOldEquation";
				break;
			case AscDFH.historydescription_Document_AddNewStyle                        :
				sString = "Document_AddNewStyle";
				break;
			case AscDFH.historydescription_Document_RemoveStyle                        :
				sString = "Document_RemoveStyle";
				break;
			case AscDFH.historydescription_Document_AddTextArt                         :
				sString = "Document_AddTextArt";
				break;
			case AscDFH.historydescription_Document_RemoveAllCustomStyles              :
				sString = "Document_RemoveAllCustomStyles";
				break;
			case AscDFH.historydescription_Document_AcceptAllRevisionChanges           :
				sString = "Document_AcceptAllRevisionChanges";
				break;
			case AscDFH.historydescription_Document_RejectAllRevisionChanges           :
				sString = "Document_RejectAllRevisionChanges";
				break;
			case AscDFH.historydescription_Document_AcceptRevisionChange               :
				sString = "Document_AcceptRevisionChange";
				break;
			case AscDFH.historydescription_Document_RejectRevisionChange               :
				sString = "Document_RejectRevisionChange";
				break;
			case AscDFH.historydescription_Document_AcceptRevisionChangesBySelection   :
				sString = "Document_AcceptRevisionChangesBySelection";
				break;
			case AscDFH.historydescription_Document_RejectRevisionChangesBySelection   :
				sString = "Document_RejectRevisionChangesBySelection";
				break;
			case AscDFH.historydescription_Document_AddLetterUnion                     :
				sString = "Document_AddLetterUnion";
				break;
			case AscDFH.historydescription_Document_SetColumnsFromRuler                :
				sString = "Document_SetColumnsFromRuler";
				break;
			case AscDFH.historydescription_Document_SetColumnsProps                    :
				sString = "Document_SetColumnsProps";
				break;
			case AscDFH.historydescription_Document_AddColumnBreak                     :
				sString = "Document_AddColumnBreak";
				break;
			case AscDFH.historydescription_Document_AddTabToMath                       :
				sString = "Document_AddTabToMath";
				break;
			case AscDFH.historydescription_Document_ApplyPrToMath:
				sString = "Document_ApplyPrToMath";
				break;
			case AscDFH.historydescription_Document_SetMathProps:
				sString = "Document_SetMathProps";
				break;
			case AscDFH.historydescription_Document_SetSectionProps:
				sString = "Document_SetColumnsProps";
				break;
			case AscDFH.historydescription_Document_ApiBuilder:
				sString = "Document_ApiBuilder";
				break;
			case AscDFH.historydescription_Document_AddOleObject:
				sString = "Document_AddOleObject";
				break;
			case AscDFH.historydescription_Document_EditOleObject:
				sString = "Document_EditOleObject";
				break;
			case AscDFH.historydescription_Document_CompositeInput:
				sString = "Document_CompositeInput";
				break;
			case AscDFH.historydescription_Document_CompositeInputReplace:
				sString = "Document_CompositeInputReplace";
				break;
			case AscDFH.historydescription_Document_AddPageCount:
				sString = "Document_AddPageCount";
				break;
			case AscDFH.historydescription_Document_AddFootnote:
				sString = "Document_AddFootnote";
				break;
			case AscDFH.historydescription_Document_SetFootnotePr:
				sString = "Document_SetFootnotePr";
				break;
			case AscDFH.historydescription_Document_RemoveAllFootnotes:
				sString = "Document_RemoveAllFootnotes";
				break;
			case AscDFH.historydescription_Document_InsertDocumentsByUrls:
				sString = "Document_InsertDocumentsByUrls";
				break;
			case AscDFH.historydescription_Document_AddBlockLevelContentControl:
				sString = "Document_AddBlockLevelContentControl";
				break;
			case AscDFH.historydescription_Document_AddInlineLevelContentControl:
				sString = "Document_AddInlineLevelContentControl";
				break;
			case AscDFH.historydescription_Document_RemoveContentControl:
				sString = "Document_RemoveContentControl";
				break;
			case AscDFH.historydescription_Document_RemoveContentControlWrapper:
				sString = "Document_RemoveContentControlWrapper";
				break;
			case AscDFH.historydescription_Document_ChangeContentControlProperties:
				sString = "Document_ChangeContentControlProperties";
				break;
			case AscDFH.historydescription_DocumentMacros_Data:
				sString = "DocumentMacros_Data";
				break;
			case AscDFH.historydescription_Document_AddBookmark:
				sString = "Document_AddBookmark";
				break;
			case AscDFH.historydescription_Document_AddTableOfContents:
				sString = "Document_AddTableOfContents";
				break;
			case AscDFH.historydescription_Document_ChangeOutlineLevel:
				sString = "Document_ChangeOutlineLevel";
				break;
			case AscDFH.historydescription_Document_AddElementToOutline:
				sString = "Document_AddElementToOutline";
				break;
			case AscDFH.historydescription_Document_ResizeTable:
				sString = "Document_ResizeTable";
				break;
			case AscDFH.historydescription_Document_RemoveComplexField:
				sString = "Document_RemoveComplexField";
				break;
			case AscDFH.historydescription_Document_SetComplexFieldPr:
				sString = "Document_SetComplexFieldPr";
				break;
			case AscDFH.historydescription_Document_UpdateTableOfContents:
				sString = "Document_UpdateTableOfContents";
				break;
			case AscDFH.historydescription_Document_SectionStartPage:
				sString = "Document_SectionStartPage";
				break;
			case AscDFH.historydescription_Document_DistributeTableCells:
				sString = "Document_DistributeTableCells";
				break;
			case AscDFH.historydescription_Document_RemoveBookmark:
				sString = "Document_RemoveBookmark";
				break;
			case AscDFH.historydescription_Document_ContinueNumbering:
				sString = "Document_ContinueNumbering";
				break;
			case AscDFH.historydescription_Document_RestartNumbering:
				sString = "Document_RestartNumbering";
				break;
			case AscDFH.historydescription_Document_AutomaticListAsType:
				sString = "Document_AutomaticListAsType";
				break;
			case AscDFH.historydescription_Document_CreateNum:
				sString = "Document_CreateNum";
				break;
			case AscDFH.historydescription_Document_ChangeNumLvl:
				sString = "Document_ChangeNumLvl";
				break;
			case AscDFH.historydescription_Document_AutoCorrectSmartQuotes:
				sString = "Document_AutoCorrectSmartQuotes";
				break;
			case AscDFH.historydescription_Document_AutoCorrectHyphensWithDash:
				sString = "Document_AutoCorrectHyphensWithDash";
				break;
			case AscDFH.historydescription_Document_SetGlobalSdtHighlightColor:
				sString = "Document_SetGlobalSdtHighlightColor";
				break;
			case AscDFH.historydescription_Document_SetGlobalSdtShowHighlight:
				sString = "Document_SetGlobalSdtShowHighlight";
				break;

		}
		return sString;
	}
	function GetHistoryClassTypeByChangeType(nChangeType)
	{
		return (nChangeType >> 16) & 0x0000FFFF;
	}

	//------------------------------------------------------------export--------------------------------------------------
	window['AscDFH']                                  = window['AscDFH'] || {};
	window['AscDFH'].GetHistoryPointStringDescription = GetHistoryPointStringDescription;
	window['AscDFH'].GetHistoryClassTypeByChangeType  = GetHistoryClassTypeByChangeType;
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Типы произошедших изменений
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].historyitem_recalctype_Inline   = 0; // Изменения произошли в обычном тексте (с верхним классом CDocument)
	window['AscDFH'].historyitem_recalctype_Flow     = 1; // Изменения произошли в "плавающем" объекте
	window['AscDFH'].historyitem_recalctype_HdrFtr   = 2; // Изменения произошли в колонтитуле
	window['AscDFH'].historyitem_recalctype_Drawing  = 3; // Изменения произошли в drawing'е
	window['AscDFH'].historyitem_recalctype_NotesEnd = 4; // Изменение произошли в сносках, которые идут в конце документа
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Типы классов, в которых происходили изменения (типы нужны для совместного редактирования)
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].historyitem_type_Unknown          = 0 << 16;
	window['AscDFH'].historyitem_type_TableId          = 1 << 16;
	window['AscDFH'].historyitem_type_Document         = 2 << 16;
	window['AscDFH'].historyitem_type_Paragraph        = 3 << 16;
	window['AscDFH'].historyitem_type_TextPr           = 4 << 16;
	window['AscDFH'].historyitem_type_Drawing          = 5 << 16;
	window['AscDFH'].historyitem_type_DrawingObjects   = 6 << 16; // obsolete
	window['AscDFH'].historyitem_type_FlowObjects      = 7 << 16; // obsolete
	window['AscDFH'].historyitem_type_FlowImage        = 8 << 16; // obsolete
	window['AscDFH'].historyitem_type_Table            = 9 << 16;
	window['AscDFH'].historyitem_type_TableRow         = 10 << 16;
	window['AscDFH'].historyitem_type_TableCell        = 11 << 16;
	window['AscDFH'].historyitem_type_DocumentContent  = 12 << 16;
	window['AscDFH'].historyitem_type_FlowTable        = 13 << 16; // obsolete
	window['AscDFH'].historyitem_type_HdrFtrController = 14 << 16; // obsolete
	window['AscDFH'].historyitem_type_HdrFtr           = 15 << 16;
	window['AscDFH'].historyitem_type_AbstractNum      = 16 << 16;
	window['AscDFH'].historyitem_type_Comment          = 17 << 16;
	window['AscDFH'].historyitem_type_Comments         = 18 << 16;
	window['AscDFH'].historyitem_type_Image            = 19 << 16;
	window['AscDFH'].historyitem_type_GrObjects        = 20 << 16;
	window['AscDFH'].historyitem_type_Hyperlink        = 21 << 16;
	window['AscDFH'].historyitem_type_Style            = 23 << 16;
	window['AscDFH'].historyitem_type_Styles           = 24 << 16;
	window['AscDFH'].historyitem_type_ChartTitle       = 25 << 16;
	window['AscDFH'].historyitem_type_Math             = 26 << 16;
	window['AscDFH'].historyitem_type_CommentMark      = 27 << 16;
	window['AscDFH'].historyitem_type_ParaRun          = 28 << 16;
	window['AscDFH'].historyitem_type_MathContent      = 29 << 16;
	window['AscDFH'].historyitem_type_Section          = 30 << 16;
	window['AscDFH'].historyitem_type_acc              = 31 << 16;
	window['AscDFH'].historyitem_type_bar              = 32 << 16;
	window['AscDFH'].historyitem_type_borderBox        = 33 << 16;
	window['AscDFH'].historyitem_type_box              = 34 << 16;
	window['AscDFH'].historyitem_type_delimiter        = 35 << 16;
	window['AscDFH'].historyitem_type_eqArr            = 36 << 16;
	window['AscDFH'].historyitem_type_frac             = 37 << 16;
	window['AscDFH'].historyitem_type_mathFunc         = 38 << 16;
	window['AscDFH'].historyitem_type_groupChr         = 39 << 16;
	window['AscDFH'].historyitem_type_lim              = 40 << 16;
	window['AscDFH'].historyitem_type_matrix           = 41 << 16;
	window['AscDFH'].historyitem_type_nary             = 42 << 16;
	window['AscDFH'].historyitem_type_integral         = 43 << 16;
	window['AscDFH'].historyitem_type_double_integral  = 44 << 16;
	window['AscDFH'].historyitem_type_triple_integral  = 45 << 16;
	window['AscDFH'].historyitem_type_contour_integral = 46 << 16;
	window['AscDFH'].historyitem_type_surface_integral = 47 << 16;
	window['AscDFH'].historyitem_type_volume_integral  = 48 << 16;
	window['AscDFH'].historyitem_type_phant            = 49 << 16;
	window['AscDFH'].historyitem_type_rad              = 50 << 16;
	window['AscDFH'].historyitem_type_deg_subsup       = 51 << 16;
	window['AscDFH'].historyitem_type_iterators        = 52 << 16;
	window['AscDFH'].historyitem_type_deg              = 53 << 16;
	window['AscDFH'].historyitem_type_ParaComment      = 54 << 16;
	window['AscDFH'].historyitem_type_Field            = 55 << 16;
	window['AscDFH'].historyitem_type_Footnotes        = 56 << 16;
	window['AscDFH'].historyitem_type_FootEndNote      = 57 << 16;
	window['AscDFH'].historyitem_type_Presentation     = 58 << 16;
	window['AscDFH'].historyitem_type_BlockLevelSdt    = 59 << 16;
	window['AscDFH'].historyitem_type_SdtPr            = 60 << 16;
	window['AscDFH'].historyitem_type_InlineLevelSdt   = 61 << 16;
	window['AscDFH'].historyitem_type_ParaBookmark     = 62 << 16;
	window['AscDFH'].historyitem_type_Num              = 63 << 16;

	window['AscDFH'].historyitem_type_CommonShape            = 1000 << 16; // Этот класс добавлен для элементов, у которых нет конкретного класса

	window['AscDFH'].historyitem_type_ColorMod               = 1001 << 16;
	window['AscDFH'].historyitem_type_ColorModifiers         = 1002 << 16;
	window['AscDFH'].historyitem_type_SysColor               = 1003 << 16;
	window['AscDFH'].historyitem_type_PrstColor              = 1004 << 16;
	window['AscDFH'].historyitem_type_RGBColor               = 1005 << 16;
	window['AscDFH'].historyitem_type_SchemeColor            = 1006 << 16;
	window['AscDFH'].historyitem_type_UniColor               = 1007 << 16;
	window['AscDFH'].historyitem_type_SrcRect                = 1008 << 16;
	window['AscDFH'].historyitem_type_BlipFill               = 1009 << 16;
	window['AscDFH'].historyitem_type_SolidFill              = 1010 << 16;
	window['AscDFH'].historyitem_type_Gs                     = 1011 << 16;
	window['AscDFH'].historyitem_type_GradLin                = 1012 << 16;
	window['AscDFH'].historyitem_type_GradPath               = 1013 << 16;
	window['AscDFH'].historyitem_type_GradFill               = 1014 << 16;
	window['AscDFH'].historyitem_type_PathFill               = 1015 << 16;
	window['AscDFH'].historyitem_type_NoFill                 = 1016 << 16;
	window['AscDFH'].historyitem_type_UniFill                = 1017 << 16;
	window['AscDFH'].historyitem_type_EndArrow               = 1018 << 16;
	window['AscDFH'].historyitem_type_LineJoin               = 1019 << 16;
	window['AscDFH'].historyitem_type_Ln                     = 1020 << 16;
	window['AscDFH'].historyitem_type_DefaultShapeDefinition = 1021 << 16;
	window['AscDFH'].historyitem_type_CNvPr                  = 1022 << 16;
	window['AscDFH'].historyitem_type_NvPr                   = 1023 << 16;
	window['AscDFH'].historyitem_type_Ph                     = 1024 << 16;
	window['AscDFH'].historyitem_type_UniNvPr                = 1025 << 16;
	window['AscDFH'].historyitem_type_StyleRef               = 1026 << 16;
	window['AscDFH'].historyitem_type_FontRef                = 1027 << 16;
	window['AscDFH'].historyitem_type_Chart                  = 1028 << 16;
	window['AscDFH'].historyitem_type_ChartSpace             = 1029 << 16;
	window['AscDFH'].historyitem_type_Legend                 = 1030 << 16;
	window['AscDFH'].historyitem_type_Layout                 = 1031 << 16;
	window['AscDFH'].historyitem_type_LegendEntry            = 1032 << 16;
	window['AscDFH'].historyitem_type_PivotFmt               = 1033 << 16;
	window['AscDFH'].historyitem_type_DLbl                   = 1034 << 16;
	window['AscDFH'].historyitem_type_Marker                 = 1035 << 16;
	window['AscDFH'].historyitem_type_PlotArea               = 1036 << 16;
	window['AscDFH'].historyitem_type_Axis                   = 1037 << 16;
	window['AscDFH'].historyitem_type_NumFmt                 = 1038 << 16;
	window['AscDFH'].historyitem_type_Scaling                = 1039 << 16;
	window['AscDFH'].historyitem_type_DTable                 = 1040 << 16;
	window['AscDFH'].historyitem_type_LineChart              = 1041 << 16;
	window['AscDFH'].historyitem_type_DLbls                  = 1042 << 16;
	window['AscDFH'].historyitem_type_UpDownBars             = 1043 << 16;
	window['AscDFH'].historyitem_type_BarChart               = 1044 << 16;
	window['AscDFH'].historyitem_type_BubbleChart            = 1045 << 16;
	window['AscDFH'].historyitem_type_DoughnutChart          = 1046 << 16;
	window['AscDFH'].historyitem_type_OfPieChart             = 1047 << 16;
	window['AscDFH'].historyitem_type_PieChart               = 1048 << 16;
	window['AscDFH'].historyitem_type_RadarChart             = 1049 << 16;
	window['AscDFH'].historyitem_type_ScatterChart           = 1050 << 16;
	window['AscDFH'].historyitem_type_StockChart             = 1051 << 16;
	window['AscDFH'].historyitem_type_SurfaceChart           = 1052 << 16;
	window['AscDFH'].historyitem_type_BandFmt                = 1053 << 16;
	window['AscDFH'].historyitem_type_AreaChart              = 1054 << 16;
	window['AscDFH'].historyitem_type_ScatterSer             = 1055 << 16;
	window['AscDFH'].historyitem_type_DPt                    = 1056 << 16;
	window['AscDFH'].historyitem_type_ErrBars                = 1057 << 16;
	window['AscDFH'].historyitem_type_MinusPlus              = 1058 << 16;
	window['AscDFH'].historyitem_type_NumLit                 = 1059 << 16;
	window['AscDFH'].historyitem_type_NumericPoint           = 1060 << 16;
	window['AscDFH'].historyitem_type_NumRef                 = 1061 << 16;
	window['AscDFH'].historyitem_type_TrendLine              = 1062 << 16;
	window['AscDFH'].historyitem_type_Tx                     = 1063 << 16;
	window['AscDFH'].historyitem_type_StrRef                 = 1064 << 16;
	window['AscDFH'].historyitem_type_StrCache               = 1065 << 16;
	window['AscDFH'].historyitem_type_StrPoint               = 1066 << 16;
	window['AscDFH'].historyitem_type_XVal                   = 1067 << 16;
	window['AscDFH'].historyitem_type_MultiLvlStrRef         = 1068 << 16;
	window['AscDFH'].historyitem_type_MultiLvlStrCache       = 1069 << 16;
	window['AscDFH'].historyitem_type_StringLiteral          = 1070 << 16;
	window['AscDFH'].historyitem_type_YVal                   = 1071 << 16;
	window['AscDFH'].historyitem_type_AreaSeries             = 1072 << 16;
	window['AscDFH'].historyitem_type_Cat                    = 1073 << 16;
	window['AscDFH'].historyitem_type_PictureOptions         = 1074 << 16;
	window['AscDFH'].historyitem_type_RadarSeries            = 1075 << 16;
	window['AscDFH'].historyitem_type_BarSeries              = 1076 << 16;
	window['AscDFH'].historyitem_type_LineSeries             = 1077 << 16;
	window['AscDFH'].historyitem_type_PieSeries              = 1078 << 16;
	window['AscDFH'].historyitem_type_SurfaceSeries          = 1079 << 16;
	window['AscDFH'].historyitem_type_BubbleSeries           = 1080 << 16;
	window['AscDFH'].historyitem_type_ExternalData           = 1081 << 16;
	window['AscDFH'].historyitem_type_PivotSource            = 1082 << 16;
	window['AscDFH'].historyitem_type_Protection             = 1083 << 16;
	window['AscDFH'].historyitem_type_ChartWall              = 1084 << 16;
	window['AscDFH'].historyitem_type_View3d                 = 1085 << 16;
	window['AscDFH'].historyitem_type_ChartText              = 1086 << 16;
	window['AscDFH'].historyitem_type_ShapeStyle             = 1087 << 16;
	window['AscDFH'].historyitem_type_Xfrm                   = 1088 << 16;
	window['AscDFH'].historyitem_type_SpPr                   = 1089 << 16;
	window['AscDFH'].historyitem_type_ClrScheme              = 1090 << 16;
	window['AscDFH'].historyitem_type_ClrMap                 = 1091 << 16;
	window['AscDFH'].historyitem_type_ExtraClrScheme         = 1092 << 16;
	window['AscDFH'].historyitem_type_FontCollection         = 1093 << 16;
	window['AscDFH'].historyitem_type_FontScheme             = 1094 << 16;
	window['AscDFH'].historyitem_type_FormatScheme           = 1095 << 16;
	window['AscDFH'].historyitem_type_ThemeElements          = 1096 << 16;
	window['AscDFH'].historyitem_type_HF                     = 1097 << 16;
	window['AscDFH'].historyitem_type_BgPr                   = 1098 << 16;
	window['AscDFH'].historyitem_type_Bg                     = 1099 << 16;
	window['AscDFH'].historyitem_type_PrintSettings          = 1100 << 16;
	window['AscDFH'].historyitem_type_HeaderFooterChart      = 1101 << 16;
	window['AscDFH'].historyitem_type_PageMarginsChart       = 1102 << 16;
	window['AscDFH'].historyitem_type_PageSetup              = 1103 << 16;
	window['AscDFH'].historyitem_type_Shape                  = 1104 << 16;
	window['AscDFH'].historyitem_type_DispUnits              = 1105 << 16;
	window['AscDFH'].historyitem_type_GroupShape             = 1106 << 16;
	window['AscDFH'].historyitem_type_ImageShape             = 1107 << 16;
	window['AscDFH'].historyitem_type_Geometry               = 1108 << 16;
	window['AscDFH'].historyitem_type_Path                   = 1109 << 16;
	window['AscDFH'].historyitem_type_TextBody               = 1110 << 16;
	window['AscDFH'].historyitem_type_CatAx                  = 1111 << 16;
	window['AscDFH'].historyitem_type_ValAx                  = 1112 << 16;
	window['AscDFH'].historyitem_type_WrapPolygon            = 1113 << 16;
	window['AscDFH'].historyitem_type_DateAx                 = 1114 << 16;
	window['AscDFH'].historyitem_type_SerAx                  = 1115 << 16;
	window['AscDFH'].historyitem_type_Title                  = 1116 << 16;
	window['AscDFH'].historyitem_type_Slide                  = 1117 << 16;
	window['AscDFH'].historyitem_type_SlideLayout            = 1118 << 16;
	window['AscDFH'].historyitem_type_SlideMaster            = 1119 << 16;
	window['AscDFH'].historyitem_type_SlideComments          = 1120 << 16;
	window['AscDFH'].historyitem_type_PropLocker             = 1121 << 16;
	window['AscDFH'].historyitem_type_Theme                  = 1122 << 16;
	window['AscDFH'].historyitem_type_GraphicFrame           = 1123 << 16;
	window['AscDFH'].historyitem_type_GrpFill                = 1124 << 16;
	window['AscDFH'].historyitem_type_OleObject              = 1125 << 16;
	window['AscDFH'].historyitem_type_DrawingContent         = 1126 << 16;
	window['AscDFH'].historyitem_type_Sparkline              = 1127 << 16;
	window['AscDFH'].historyitem_type_NotesMaster            = 1128 << 16;
	window['AscDFH'].historyitem_type_Notes                  = 1129 << 16;
	window['AscDFH'].historyitem_type_Cnx                    = 1130 << 16;
	window['AscDFH'].historyitem_type_PresentationSection    = 1131 << 16;
	window['AscDFH'].historyitem_type_PivotTableDefinition   = 1132 << 16;

	window['AscDFH'].historyitem_type_DocumentMacros         = 2000 << 16;
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Типы изменений, разбитые по классам
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].historyitem_Unknown_Unknown = window['AscDFH'].historyitem_type_Unknown | 0;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CTableId
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_TableId_Add         = window['AscDFH'].historyitem_type_TableId | 1;
	window['AscDFH'].historyitem_TableId_Description = window['AscDFH'].historyitem_type_TableId | 0xFFFF;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CDocument
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Document_AddItem           = window['AscDFH'].historyitem_type_Document | 1;
	window['AscDFH'].historyitem_Document_RemoveItem        = window['AscDFH'].historyitem_type_Document | 2;
	window['AscDFH'].historyitem_Document_DefaultTab        = window['AscDFH'].historyitem_type_Document | 3;
	window['AscDFH'].historyitem_Document_EvenAndOddHeaders = window['AscDFH'].historyitem_type_Document | 4;
	window['AscDFH'].historyitem_Document_DefaultLanguage   = window['AscDFH'].historyitem_type_Document | 5;
	window['AscDFH'].historyitem_Document_MathSettings      = window['AscDFH'].historyitem_type_Document | 6;
	window['AscDFH'].historyitem_Document_SdtGlobalSettings = window['AscDFH'].historyitem_type_Document | 7;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе Paragraph
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Paragraph_AddItem                   = window['AscDFH'].historyitem_type_Paragraph | 1;
	window['AscDFH'].historyitem_Paragraph_RemoveItem                = window['AscDFH'].historyitem_type_Paragraph | 2;
	window['AscDFH'].historyitem_Paragraph_Numbering                 = window['AscDFH'].historyitem_type_Paragraph | 3;
	window['AscDFH'].historyitem_Paragraph_Align                     = window['AscDFH'].historyitem_type_Paragraph | 4;
	window['AscDFH'].historyitem_Paragraph_Ind_First                 = window['AscDFH'].historyitem_type_Paragraph | 5;
	window['AscDFH'].historyitem_Paragraph_Ind_Right                 = window['AscDFH'].historyitem_type_Paragraph | 6;
	window['AscDFH'].historyitem_Paragraph_Ind_Left                  = window['AscDFH'].historyitem_type_Paragraph | 7;
	window['AscDFH'].historyitem_Paragraph_ContextualSpacing         = window['AscDFH'].historyitem_type_Paragraph | 8;
	window['AscDFH'].historyitem_Paragraph_KeepLines                 = window['AscDFH'].historyitem_type_Paragraph | 9;
	window['AscDFH'].historyitem_Paragraph_KeepNext                  = window['AscDFH'].historyitem_type_Paragraph | 10;
	window['AscDFH'].historyitem_Paragraph_PageBreakBefore           = window['AscDFH'].historyitem_type_Paragraph | 11;
	window['AscDFH'].historyitem_Paragraph_Spacing_Line              = window['AscDFH'].historyitem_type_Paragraph | 12;
	window['AscDFH'].historyitem_Paragraph_Spacing_LineRule          = window['AscDFH'].historyitem_type_Paragraph | 13;
	window['AscDFH'].historyitem_Paragraph_Spacing_Before            = window['AscDFH'].historyitem_type_Paragraph | 14;
	window['AscDFH'].historyitem_Paragraph_Spacing_After             = window['AscDFH'].historyitem_type_Paragraph | 15;
	window['AscDFH'].historyitem_Paragraph_Spacing_AfterAutoSpacing  = window['AscDFH'].historyitem_type_Paragraph | 16;
	window['AscDFH'].historyitem_Paragraph_Spacing_BeforeAutoSpacing = window['AscDFH'].historyitem_type_Paragraph | 17;
	window['AscDFH'].historyitem_Paragraph_Shd_Value                 = window['AscDFH'].historyitem_type_Paragraph | 18;
	window['AscDFH'].historyitem_Paragraph_Shd_Color                 = window['AscDFH'].historyitem_type_Paragraph | 19;
	window['AscDFH'].historyitem_Paragraph_Shd_Unifill               = window['AscDFH'].historyitem_type_Paragraph | 20;
	window['AscDFH'].historyitem_Paragraph_Shd                       = window['AscDFH'].historyitem_type_Paragraph | 21;
	window['AscDFH'].historyitem_Paragraph_WidowControl              = window['AscDFH'].historyitem_type_Paragraph | 22;
	window['AscDFH'].historyitem_Paragraph_Tabs                      = window['AscDFH'].historyitem_type_Paragraph | 23;
	window['AscDFH'].historyitem_Paragraph_PStyle                    = window['AscDFH'].historyitem_type_Paragraph | 24;
	window['AscDFH'].historyitem_Paragraph_Borders_Between           = window['AscDFH'].historyitem_type_Paragraph | 25;
	window['AscDFH'].historyitem_Paragraph_Borders_Bottom            = window['AscDFH'].historyitem_type_Paragraph | 26;
	window['AscDFH'].historyitem_Paragraph_Borders_Left              = window['AscDFH'].historyitem_type_Paragraph | 27;
	window['AscDFH'].historyitem_Paragraph_Borders_Right             = window['AscDFH'].historyitem_type_Paragraph | 28;
	window['AscDFH'].historyitem_Paragraph_Borders_Top               = window['AscDFH'].historyitem_type_Paragraph | 29;
	window['AscDFH'].historyitem_Paragraph_Pr                        = window['AscDFH'].historyitem_type_Paragraph | 30;
	window['AscDFH'].historyitem_Paragraph_PresentationPr_Bullet     = window['AscDFH'].historyitem_type_Paragraph | 31;
	window['AscDFH'].historyitem_Paragraph_PresentationPr_Level      = window['AscDFH'].historyitem_type_Paragraph | 32;
	window['AscDFH'].historyitem_Paragraph_FramePr                   = window['AscDFH'].historyitem_type_Paragraph | 33;
	window['AscDFH'].historyitem_Paragraph_SectionPr                 = window['AscDFH'].historyitem_type_Paragraph | 34;
	window['AscDFH'].historyitem_Paragraph_PrChange                  = window['AscDFH'].historyitem_type_Paragraph | 35;
	window['AscDFH'].historyitem_Paragraph_PrReviewInfo              = window['AscDFH'].historyitem_type_Paragraph | 36;
	window['AscDFH'].historyitem_Paragraph_OutlineLvl                = window['AscDFH'].historyitem_type_Paragraph | 37;
	window['AscDFH'].historyitem_Paragraph_DefaultTabSize            = window['AscDFH'].historyitem_type_Paragraph | 38;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaTextPr
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_TextPr_Bold            = window['AscDFH'].historyitem_type_TextPr | 1;
	window['AscDFH'].historyitem_TextPr_Italic          = window['AscDFH'].historyitem_type_TextPr | 2;
	window['AscDFH'].historyitem_TextPr_Strikeout       = window['AscDFH'].historyitem_type_TextPr | 3;
	window['AscDFH'].historyitem_TextPr_Underline       = window['AscDFH'].historyitem_type_TextPr | 4;
	window['AscDFH'].historyitem_TextPr_FontSize        = window['AscDFH'].historyitem_type_TextPr | 5;
	window['AscDFH'].historyitem_TextPr_Color           = window['AscDFH'].historyitem_type_TextPr | 6;
	window['AscDFH'].historyitem_TextPr_VertAlign       = window['AscDFH'].historyitem_type_TextPr | 7;
	window['AscDFH'].historyitem_TextPr_HighLight       = window['AscDFH'].historyitem_type_TextPr | 8;
	window['AscDFH'].historyitem_TextPr_RStyle          = window['AscDFH'].historyitem_type_TextPr | 9;
	window['AscDFH'].historyitem_TextPr_Spacing         = window['AscDFH'].historyitem_type_TextPr | 10;
	window['AscDFH'].historyitem_TextPr_DStrikeout      = window['AscDFH'].historyitem_type_TextPr | 11;
	window['AscDFH'].historyitem_TextPr_Caps            = window['AscDFH'].historyitem_type_TextPr | 12;
	window['AscDFH'].historyitem_TextPr_SmallCaps       = window['AscDFH'].historyitem_type_TextPr | 13;
	window['AscDFH'].historyitem_TextPr_Position        = window['AscDFH'].historyitem_type_TextPr | 14;
	window['AscDFH'].historyitem_TextPr_Value           = window['AscDFH'].historyitem_type_TextPr | 15;
	window['AscDFH'].historyitem_TextPr_RFonts          = window['AscDFH'].historyitem_type_TextPr | 16;
	window['AscDFH'].historyitem_TextPr_RFonts_Ascii    = window['AscDFH'].historyitem_type_TextPr | 17;
	window['AscDFH'].historyitem_TextPr_RFonts_HAnsi    = window['AscDFH'].historyitem_type_TextPr | 18;
	window['AscDFH'].historyitem_TextPr_RFonts_CS       = window['AscDFH'].historyitem_type_TextPr | 19;
	window['AscDFH'].historyitem_TextPr_RFonts_EastAsia = window['AscDFH'].historyitem_type_TextPr | 20;
	window['AscDFH'].historyitem_TextPr_RFonts_Hint     = window['AscDFH'].historyitem_type_TextPr | 21;
	window['AscDFH'].historyitem_TextPr_Lang            = window['AscDFH'].historyitem_type_TextPr | 22;
	window['AscDFH'].historyitem_TextPr_Lang_Bidi       = window['AscDFH'].historyitem_type_TextPr | 23;
	window['AscDFH'].historyitem_TextPr_Lang_EastAsia   = window['AscDFH'].historyitem_type_TextPr | 24;
	window['AscDFH'].historyitem_TextPr_Lang_Val        = window['AscDFH'].historyitem_type_TextPr | 25;
	window['AscDFH'].historyitem_TextPr_Unifill         = window['AscDFH'].historyitem_type_TextPr | 26;
	window['AscDFH'].historyitem_TextPr_FontSizeCS      = window['AscDFH'].historyitem_type_TextPr | 27;
	window['AscDFH'].historyitem_TextPr_Outline         = window['AscDFH'].historyitem_type_TextPr | 28;
	window['AscDFH'].historyitem_TextPr_Fill            = window['AscDFH'].historyitem_type_TextPr | 29;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaDrawing
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Drawing_DrawingType       = window['AscDFH'].historyitem_type_Drawing | 1;
	window['AscDFH'].historyitem_Drawing_WrappingType      = window['AscDFH'].historyitem_type_Drawing | 2;
	window['AscDFH'].historyitem_Drawing_Distance          = window['AscDFH'].historyitem_type_Drawing | 3;
	window['AscDFH'].historyitem_Drawing_AllowOverlap      = window['AscDFH'].historyitem_type_Drawing | 4;
	window['AscDFH'].historyitem_Drawing_PositionH         = window['AscDFH'].historyitem_type_Drawing | 5;
	window['AscDFH'].historyitem_Drawing_PositionV         = window['AscDFH'].historyitem_type_Drawing | 6;
	window['AscDFH'].historyitem_Drawing_BehindDoc         = window['AscDFH'].historyitem_type_Drawing | 7;
	window['AscDFH'].historyitem_Drawing_SetGraphicObject  = window['AscDFH'].historyitem_type_Drawing | 8;
	window['AscDFH'].historyitem_Drawing_SetSimplePos      = window['AscDFH'].historyitem_type_Drawing | 9;
	window['AscDFH'].historyitem_Drawing_SetExtent         = window['AscDFH'].historyitem_type_Drawing | 10;
	window['AscDFH'].historyitem_Drawing_SetWrapPolygon    = window['AscDFH'].historyitem_type_Drawing | 11;
	window['AscDFH'].historyitem_Drawing_SetLocked         = window['AscDFH'].historyitem_type_Drawing | 12;
	window['AscDFH'].historyitem_Drawing_SetRelativeHeight = window['AscDFH'].historyitem_type_Drawing | 13;
	window['AscDFH'].historyitem_Drawing_SetEffectExtent   = window['AscDFH'].historyitem_type_Drawing | 14;
	window['AscDFH'].historyitem_Drawing_SetParent         = window['AscDFH'].historyitem_type_Drawing | 15;
	window['AscDFH'].historyitem_Drawing_SetParaMath       = window['AscDFH'].historyitem_type_Drawing | 16;
	window['AscDFH'].historyitem_Drawing_LayoutInCell      = window['AscDFH'].historyitem_type_Drawing | 17;
	window['AscDFH'].historyitem_Drawing_SetSizeRelH       = window['AscDFH'].historyitem_type_Drawing | 18;
	window['AscDFH'].historyitem_Drawing_SetSizeRelV       = window['AscDFH'].historyitem_type_Drawing | 19;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CTable
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Table_TableW                = window['AscDFH'].historyitem_type_Table | 1;
	window['AscDFH'].historyitem_Table_TableCellMar          = window['AscDFH'].historyitem_type_Table | 2;
	window['AscDFH'].historyitem_Table_TableAlign            = window['AscDFH'].historyitem_type_Table | 3;
	window['AscDFH'].historyitem_Table_TableInd              = window['AscDFH'].historyitem_type_Table | 4;
	window['AscDFH'].historyitem_Table_TableBorder_Left      = window['AscDFH'].historyitem_type_Table | 5;
	window['AscDFH'].historyitem_Table_TableBorder_Top       = window['AscDFH'].historyitem_type_Table | 6;
	window['AscDFH'].historyitem_Table_TableBorder_Right     = window['AscDFH'].historyitem_type_Table | 7;
	window['AscDFH'].historyitem_Table_TableBorder_Bottom    = window['AscDFH'].historyitem_type_Table | 8;
	window['AscDFH'].historyitem_Table_TableBorder_InsideH   = window['AscDFH'].historyitem_type_Table | 9;
	window['AscDFH'].historyitem_Table_TableBorder_InsideV   = window['AscDFH'].historyitem_type_Table | 10;
	window['AscDFH'].historyitem_Table_TableShd              = window['AscDFH'].historyitem_type_Table | 11;
	window['AscDFH'].historyitem_Table_Inline                = window['AscDFH'].historyitem_type_Table | 12;
	window['AscDFH'].historyitem_Table_AddRow                = window['AscDFH'].historyitem_type_Table | 13;
	window['AscDFH'].historyitem_Table_RemoveRow             = window['AscDFH'].historyitem_type_Table | 14;
	window['AscDFH'].historyitem_Table_TableGrid             = window['AscDFH'].historyitem_type_Table | 15;
	window['AscDFH'].historyitem_Table_TableLook             = window['AscDFH'].historyitem_type_Table | 16;
	window['AscDFH'].historyitem_Table_TableStyleRowBandSize = window['AscDFH'].historyitem_type_Table | 17;
	window['AscDFH'].historyitem_Table_TableStyleColBandSize = window['AscDFH'].historyitem_type_Table | 18;
	window['AscDFH'].historyitem_Table_TableStyle            = window['AscDFH'].historyitem_type_Table | 19;
	window['AscDFH'].historyitem_Table_AllowOverlap          = window['AscDFH'].historyitem_type_Table | 20;
	window['AscDFH'].historyitem_Table_PositionH             = window['AscDFH'].historyitem_type_Table | 21;
	window['AscDFH'].historyitem_Table_PositionV             = window['AscDFH'].historyitem_type_Table | 22;
	window['AscDFH'].historyitem_Table_Distance              = window['AscDFH'].historyitem_type_Table | 23;
	window['AscDFH'].historyitem_Table_Pr                    = window['AscDFH'].historyitem_type_Table | 24;
	window['AscDFH'].historyitem_Table_TableLayout           = window['AscDFH'].historyitem_type_Table | 25;
	window['AscDFH'].historyitem_Table_TableDescription      = window['AscDFH'].historyitem_type_Table | 26;
	window['AscDFH'].historyitem_Table_TableCaption          = window['AscDFH'].historyitem_type_Table | 27;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CTableRow
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_TableRow_Before      = window['AscDFH'].historyitem_type_TableRow | 1;
	window['AscDFH'].historyitem_TableRow_After       = window['AscDFH'].historyitem_type_TableRow | 2;
	window['AscDFH'].historyitem_TableRow_CellSpacing = window['AscDFH'].historyitem_type_TableRow | 3;
	window['AscDFH'].historyitem_TableRow_Height      = window['AscDFH'].historyitem_type_TableRow | 4;
	window['AscDFH'].historyitem_TableRow_AddCell     = window['AscDFH'].historyitem_type_TableRow | 5;
	window['AscDFH'].historyitem_TableRow_RemoveCell  = window['AscDFH'].historyitem_type_TableRow | 6;
	window['AscDFH'].historyitem_TableRow_TableHeader = window['AscDFH'].historyitem_type_TableRow | 7;
	window['AscDFH'].historyitem_TableRow_Pr          = window['AscDFH'].historyitem_type_TableRow | 8;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CTableCell
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_TableCell_GridSpan      = window['AscDFH'].historyitem_type_TableCell | 1;
	window['AscDFH'].historyitem_TableCell_Margins       = window['AscDFH'].historyitem_type_TableCell | 2;
	window['AscDFH'].historyitem_TableCell_Shd           = window['AscDFH'].historyitem_type_TableCell | 3;
	window['AscDFH'].historyitem_TableCell_VMerge        = window['AscDFH'].historyitem_type_TableCell | 4;
	window['AscDFH'].historyitem_TableCell_Border_Left   = window['AscDFH'].historyitem_type_TableCell | 5;
	window['AscDFH'].historyitem_TableCell_Border_Right  = window['AscDFH'].historyitem_type_TableCell | 6;
	window['AscDFH'].historyitem_TableCell_Border_Top    = window['AscDFH'].historyitem_type_TableCell | 7;
	window['AscDFH'].historyitem_TableCell_Border_Bottom = window['AscDFH'].historyitem_type_TableCell | 8;
	window['AscDFH'].historyitem_TableCell_VAlign        = window['AscDFH'].historyitem_type_TableCell | 9;
	window['AscDFH'].historyitem_TableCell_W             = window['AscDFH'].historyitem_type_TableCell | 10;
	window['AscDFH'].historyitem_TableCell_Pr            = window['AscDFH'].historyitem_type_TableCell | 11;
	window['AscDFH'].historyitem_TableCell_TextDirection = window['AscDFH'].historyitem_type_TableCell | 12;
	window['AscDFH'].historyitem_TableCell_NoWrap        = window['AscDFH'].historyitem_type_TableCell | 13;
	window['AscDFH'].historyitem_TableCell_HMerge        = window['AscDFH'].historyitem_type_TableCell | 14;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CDocumentContent
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_DocumentContent_AddItem    = window['AscDFH'].historyitem_type_DocumentContent | 1;
	window['AscDFH'].historyitem_DocumentContent_RemoveItem = window['AscDFH'].historyitem_type_DocumentContent | 2;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CAbstractNum
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_AbstractNum_LvlChange    = window['AscDFH'].historyitem_type_AbstractNum | 1;
	window['AscDFH'].historyitem_AbstractNum_TextPrChange = window['AscDFH'].historyitem_type_AbstractNum | 2;
	window['AscDFH'].historyitem_AbstractNum_ParaPrChange = window['AscDFH'].historyitem_type_AbstractNum | 3;
	window['AscDFH'].historyitem_AbstractNum_StyleLink    = window['AscDFH'].historyitem_type_AbstractNum | 4;
	window['AscDFH'].historyitem_AbstractNum_NumStyleLink = window['AscDFH'].historyitem_type_AbstractNum | 5;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CNum
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Num_LvlOverrideChange = window['AscDFH'].historyitem_type_Num | 1;
	window['AscDFH'].historyitem_Num_AbstractNum       = window['AscDFH'].historyitem_type_Num | 2;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе СComment
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Comment_Change   = window['AscDFH'].historyitem_type_Comment | 1;
	window['AscDFH'].historyitem_Comment_TypeInfo = window['AscDFH'].historyitem_type_Comment | 2;
	window['AscDFH'].historyitem_Comment_Position = window['AscDFH'].historyitem_type_Comment | 3;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CComments
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Comments_Add    = window['AscDFH'].historyitem_type_Comments | 1;
	window['AscDFH'].historyitem_Comments_Remove = window['AscDFH'].historyitem_type_Comments | 2;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaHyperlink
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Hyperlink_Value      = window['AscDFH'].historyitem_type_Hyperlink | 1;
	window['AscDFH'].historyitem_Hyperlink_ToolTip    = window['AscDFH'].historyitem_type_Hyperlink | 2;
	window['AscDFH'].historyitem_Hyperlink_AddItem    = window['AscDFH'].historyitem_type_Hyperlink | 3;
	window['AscDFH'].historyitem_Hyperlink_RemoveItem = window['AscDFH'].historyitem_type_Hyperlink | 4;
	window['AscDFH'].historyitem_Hyperlink_Anchor     = window['AscDFH'].historyitem_type_Hyperlink | 5;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CStyle
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Style_TextPr          = window['AscDFH'].historyitem_type_Style | 1;
	window['AscDFH'].historyitem_Style_ParaPr          = window['AscDFH'].historyitem_type_Style | 2;
	window['AscDFH'].historyitem_Style_TablePr         = window['AscDFH'].historyitem_type_Style | 3;
	window['AscDFH'].historyitem_Style_TableRowPr      = window['AscDFH'].historyitem_type_Style | 4;
	window['AscDFH'].historyitem_Style_TableCellPr     = window['AscDFH'].historyitem_type_Style | 5;
	window['AscDFH'].historyitem_Style_TableBand1Horz  = window['AscDFH'].historyitem_type_Style | 6;
	window['AscDFH'].historyitem_Style_TableBand1Vert  = window['AscDFH'].historyitem_type_Style | 7;
	window['AscDFH'].historyitem_Style_TableBand2Horz  = window['AscDFH'].historyitem_type_Style | 8;
	window['AscDFH'].historyitem_Style_TableBand2Vert  = window['AscDFH'].historyitem_type_Style | 9;
	window['AscDFH'].historyitem_Style_TableFirstCol   = window['AscDFH'].historyitem_type_Style | 10;
	window['AscDFH'].historyitem_Style_TableFirstRow   = window['AscDFH'].historyitem_type_Style | 11;
	window['AscDFH'].historyitem_Style_TableLastCol    = window['AscDFH'].historyitem_type_Style | 12;
	window['AscDFH'].historyitem_Style_TableLastRow    = window['AscDFH'].historyitem_type_Style | 13;
	window['AscDFH'].historyitem_Style_TableTLCell     = window['AscDFH'].historyitem_type_Style | 14;
	window['AscDFH'].historyitem_Style_TableTRCell     = window['AscDFH'].historyitem_type_Style | 15;
	window['AscDFH'].historyitem_Style_TableBLCell     = window['AscDFH'].historyitem_type_Style | 16;
	window['AscDFH'].historyitem_Style_TableBRCell     = window['AscDFH'].historyitem_type_Style | 17;
	window['AscDFH'].historyitem_Style_TableWholeTable = window['AscDFH'].historyitem_type_Style | 18;
	window['AscDFH'].historyitem_Style_Name            = window['AscDFH'].historyitem_type_Style | 101;
	window['AscDFH'].historyitem_Style_BasedOn         = window['AscDFH'].historyitem_type_Style | 102;
	window['AscDFH'].historyitem_Style_Next            = window['AscDFH'].historyitem_type_Style | 103;
	window['AscDFH'].historyitem_Style_Type            = window['AscDFH'].historyitem_type_Style | 104;
	window['AscDFH'].historyitem_Style_QFormat         = window['AscDFH'].historyitem_type_Style | 105;
	window['AscDFH'].historyitem_Style_UiPriority      = window['AscDFH'].historyitem_type_Style | 106;
	window['AscDFH'].historyitem_Style_Hidden          = window['AscDFH'].historyitem_type_Style | 107;
	window['AscDFH'].historyitem_Style_SemiHidden      = window['AscDFH'].historyitem_type_Style | 108;
	window['AscDFH'].historyitem_Style_UnhideWhenUsed  = window['AscDFH'].historyitem_type_Style | 109;
	window['AscDFH'].historyitem_Style_Link            = window['AscDFH'].historyitem_type_Style | 110;
	window['AscDFH'].historyitem_Style_Custom          = window['AscDFH'].historyitem_type_Style | 111;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CStyles
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Styles_Add                              = window['AscDFH'].historyitem_type_Styles | 1;
	window['AscDFH'].historyitem_Styles_Remove                           = window['AscDFH'].historyitem_type_Styles | 2;
	window['AscDFH'].historyitem_Styles_ChangeDefaultTextPr              = window['AscDFH'].historyitem_type_Styles | 3;
	window['AscDFH'].historyitem_Styles_ChangeDefaultParaPr              = window['AscDFH'].historyitem_type_Styles | 4;
	window['AscDFH'].historyitem_Styles_ChangeDefaultParagraphId         = window['AscDFH'].historyitem_type_Styles | 5;
	window['AscDFH'].historyitem_Styles_ChangeDefaultCharacterId         = window['AscDFH'].historyitem_type_Styles | 6;
	window['AscDFH'].historyitem_Styles_ChangeDefaultNumberingId         = window['AscDFH'].historyitem_type_Styles | 7;
	window['AscDFH'].historyitem_Styles_ChangeDefaultTableId             = window['AscDFH'].historyitem_type_Styles | 8;
	window['AscDFH'].historyitem_Styles_ChangeDefaultTableGridId         = window['AscDFH'].historyitem_type_Styles | 9;
	window['AscDFH'].historyitem_Styles_ChangeDefaultHeadingsId          = window['AscDFH'].historyitem_type_Styles | 10;
	window['AscDFH'].historyitem_Styles_ChangeDefaultParaListId          = window['AscDFH'].historyitem_type_Styles | 11;
	window['AscDFH'].historyitem_Styles_ChangeDefaultHeaderId            = window['AscDFH'].historyitem_type_Styles | 12;
	window['AscDFH'].historyitem_Styles_ChangeDefaultFooterId            = window['AscDFH'].historyitem_type_Styles | 13;
	window['AscDFH'].historyitem_Styles_ChangeDefaultHyperlinkId         = window['AscDFH'].historyitem_type_Styles | 14;
	window['AscDFH'].historyitem_Styles_ChangeDefaultFootnoteTextId      = window['AscDFH'].historyitem_type_Styles | 15;
	window['AscDFH'].historyitem_Styles_ChangeDefaultFootnoteTextCharId  = window['AscDFH'].historyitem_type_Styles | 16;
	window['AscDFH'].historyitem_Styles_ChangeDefaultFootnoteReferenceId = window['AscDFH'].historyitem_type_Styles | 17;
	window['AscDFH'].historyitem_Styles_ChangeDefaultNoSpacingId         = window['AscDFH'].historyitem_type_Styles | 18;
	window['AscDFH'].historyitem_Styles_ChangeDefaultTitleId             = window['AscDFH'].historyitem_type_Styles | 19;
	window['AscDFH'].historyitem_Styles_ChangeDefaultSubtitleId          = window['AscDFH'].historyitem_type_Styles | 20;
	window['AscDFH'].historyitem_Styles_ChangeDefaultQuoteId             = window['AscDFH'].historyitem_type_Styles | 21;
	window['AscDFH'].historyitem_Styles_ChangeDefaultIntenseQuoteId      = window['AscDFH'].historyitem_type_Styles | 22;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaMath
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_MathContent_AddItem      = window['AscDFH'].historyitem_type_Math | 101;
	window['AscDFH'].historyitem_MathContent_RemoveItem   = window['AscDFH'].historyitem_type_Math | 102;
	window['AscDFH'].historyitem_MathContent_ArgSize      = window['AscDFH'].historyitem_type_Math | 103;
	window['AscDFH'].historyitem_MathPara_Jc              = window['AscDFH'].historyitem_type_Math | 201;
	window['AscDFH'].historyitem_MathBase_AddItems        = window['AscDFH'].historyitem_type_Math | 301;
	window['AscDFH'].historyitem_MathBase_RemoveItems     = window['AscDFH'].historyitem_type_Math | 302;
	window['AscDFH'].historyitem_MathBase_FontSize        = window['AscDFH'].historyitem_type_Math | 303;
	window['AscDFH'].historyitem_MathBase_Shd             = window['AscDFH'].historyitem_type_Math | 304;
	window['AscDFH'].historyitem_MathBase_Color           = window['AscDFH'].historyitem_type_Math | 305;
	window['AscDFH'].historyitem_MathBase_Unifill         = window['AscDFH'].historyitem_type_Math | 306;
	window['AscDFH'].historyitem_MathBase_Underline       = window['AscDFH'].historyitem_type_Math | 307;
	window['AscDFH'].historyitem_MathBase_Strikeout       = window['AscDFH'].historyitem_type_Math | 308;
	window['AscDFH'].historyitem_MathBase_DoubleStrikeout = window['AscDFH'].historyitem_type_Math | 309;
	window['AscDFH'].historyitem_MathBase_Italic          = window['AscDFH'].historyitem_type_Math | 310;
	window['AscDFH'].historyitem_MathBase_Bold            = window['AscDFH'].historyitem_type_Math | 311;
	window['AscDFH'].historyitem_MathBase_RFontsAscii     = window['AscDFH'].historyitem_type_Math | 312;
	window['AscDFH'].historyitem_MathBase_RFontsHAnsi     = window['AscDFH'].historyitem_type_Math | 313;
	window['AscDFH'].historyitem_MathBase_RFontsCS        = window['AscDFH'].historyitem_type_Math | 314;
	window['AscDFH'].historyitem_MathBase_RFontsEastAsia  = window['AscDFH'].historyitem_type_Math | 315;
	window['AscDFH'].historyitem_MathBase_RFontsHint      = window['AscDFH'].historyitem_type_Math | 316;
	window['AscDFH'].historyitem_MathBase_HighLight       = window['AscDFH'].historyitem_type_Math | 317;
	window['AscDFH'].historyitem_MathBase_ReviewType      = window['AscDFH'].historyitem_type_Math | 318;
	window['AscDFH'].historyitem_MathBase_TextFill        = window['AscDFH'].historyitem_type_Math | 319;
	window['AscDFH'].historyitem_MathBase_TextOutline     = window['AscDFH'].historyitem_type_Math | 320;
	window['AscDFH'].historyitem_MathBox_AlnAt            = window['AscDFH'].historyitem_type_Math | 401;
	window['AscDFH'].historyitem_MathBox_ForcedBreak      = window['AscDFH'].historyitem_type_Math | 402;
	window['AscDFH'].historyitem_MathFraction_Type        = window['AscDFH'].historyitem_type_Math | 501;
	window['AscDFH'].historyitem_MathRadical_HideDegree   = window['AscDFH'].historyitem_type_Math | 601;
	window['AscDFH'].historyitem_MathNary_LimLoc          = window['AscDFH'].historyitem_type_Math | 701;
	window['AscDFH'].historyitem_MathNary_UpperLimit      = window['AscDFH'].historyitem_type_Math | 702;
	window['AscDFH'].historyitem_MathNary_LowerLimit      = window['AscDFH'].historyitem_type_Math | 703;
	window['AscDFH'].historyitem_MathDelimiter_BegOper    = window['AscDFH'].historyitem_type_Math | 801;
	window['AscDFH'].historyitem_MathDelimiter_EndOper    = window['AscDFH'].historyitem_type_Math | 802;
	window['AscDFH'].historyitem_MathDelimiter_Grow       = window['AscDFH'].historyitem_type_Math | 803;
	window['AscDFH'].historyitem_MathDelimiter_Shape      = window['AscDFH'].historyitem_type_Math | 804;
	window['AscDFH'].historyitem_MathDelimiter_SetColumn  = window['AscDFH'].historyitem_type_Math | 805;
	window['AscDFH'].historyitem_MathGroupChar_Pr         = window['AscDFH'].historyitem_type_Math | 901;
	window['AscDFH'].historyitem_MathLimit_Type           = window['AscDFH'].historyitem_type_Math | 1001;
	window['AscDFH'].historyitem_MathBorderBox_Top        = window['AscDFH'].historyitem_type_Math | 1101;
	window['AscDFH'].historyitem_MathBorderBox_Bot        = window['AscDFH'].historyitem_type_Math | 1102;
	window['AscDFH'].historyitem_MathBorderBox_Left       = window['AscDFH'].historyitem_type_Math | 1103;
	window['AscDFH'].historyitem_MathBorderBox_Right      = window['AscDFH'].historyitem_type_Math | 1104;
	window['AscDFH'].historyitem_MathBorderBox_Hor        = window['AscDFH'].historyitem_type_Math | 1105;
	window['AscDFH'].historyitem_MathBorderBox_Ver        = window['AscDFH'].historyitem_type_Math | 1106;
	window['AscDFH'].historyitem_MathBorderBox_TopLTR     = window['AscDFH'].historyitem_type_Math | 1107;
	window['AscDFH'].historyitem_MathBorderBox_TopRTL     = window['AscDFH'].historyitem_type_Math | 1108;
	window['AscDFH'].historyitem_MathBar_LinePos          = window['AscDFH'].historyitem_type_Math | 1201;
	window['AscDFH'].historyitem_MathMatrix_AddRow        = window['AscDFH'].historyitem_type_Math | 1301;
	window['AscDFH'].historyitem_MathMatrix_RemoveRow     = window['AscDFH'].historyitem_type_Math | 1302;
	window['AscDFH'].historyitem_MathMatrix_AddColumn     = window['AscDFH'].historyitem_type_Math | 1303;
	window['AscDFH'].historyitem_MathMatrix_RemoveColumn  = window['AscDFH'].historyitem_type_Math | 1304;
	window['AscDFH'].historyitem_MathMatrix_BaseJc        = window['AscDFH'].historyitem_type_Math | 1305;
	window['AscDFH'].historyitem_MathMatrix_ColumnJc      = window['AscDFH'].historyitem_type_Math | 1306;
	window['AscDFH'].historyitem_MathMatrix_Interval      = window['AscDFH'].historyitem_type_Math | 1307;
	window['AscDFH'].historyitem_MathMatrix_Plh           = window['AscDFH'].historyitem_type_Math | 1308;
	window['AscDFH'].historyitem_MathDegree_SubSupType    = window['AscDFH'].historyitem_type_Math | 1401;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaRun
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_ParaRun_AddItem           = window['AscDFH'].historyitem_type_ParaRun | 1;
	window['AscDFH'].historyitem_ParaRun_RemoveItem        = window['AscDFH'].historyitem_type_ParaRun | 2;
	window['AscDFH'].historyitem_ParaRun_Bold              = window['AscDFH'].historyitem_type_ParaRun | 3;
	window['AscDFH'].historyitem_ParaRun_Italic            = window['AscDFH'].historyitem_type_ParaRun | 4;
	window['AscDFH'].historyitem_ParaRun_Strikeout         = window['AscDFH'].historyitem_type_ParaRun | 5;
	window['AscDFH'].historyitem_ParaRun_Underline         = window['AscDFH'].historyitem_type_ParaRun | 6;
	window['AscDFH'].historyitem_ParaRun_FontFamily        = window['AscDFH'].historyitem_type_ParaRun | 7; // obsolete
	window['AscDFH'].historyitem_ParaRun_FontSize          = window['AscDFH'].historyitem_type_ParaRun | 8;
	window['AscDFH'].historyitem_ParaRun_Color             = window['AscDFH'].historyitem_type_ParaRun | 9;
	window['AscDFH'].historyitem_ParaRun_VertAlign         = window['AscDFH'].historyitem_type_ParaRun | 10;
	window['AscDFH'].historyitem_ParaRun_HighLight         = window['AscDFH'].historyitem_type_ParaRun | 11;
	window['AscDFH'].historyitem_ParaRun_RStyle            = window['AscDFH'].historyitem_type_ParaRun | 12;
	window['AscDFH'].historyitem_ParaRun_Spacing           = window['AscDFH'].historyitem_type_ParaRun | 13;
	window['AscDFH'].historyitem_ParaRun_DStrikeout        = window['AscDFH'].historyitem_type_ParaRun | 14;
	window['AscDFH'].historyitem_ParaRun_Caps              = window['AscDFH'].historyitem_type_ParaRun | 15;
	window['AscDFH'].historyitem_ParaRun_SmallCaps         = window['AscDFH'].historyitem_type_ParaRun | 16;
	window['AscDFH'].historyitem_ParaRun_Position          = window['AscDFH'].historyitem_type_ParaRun | 17;
	window['AscDFH'].historyitem_ParaRun_Value             = window['AscDFH'].historyitem_type_ParaRun | 18; // obsolete
	window['AscDFH'].historyitem_ParaRun_RFonts            = window['AscDFH'].historyitem_type_ParaRun | 19;
	window['AscDFH'].historyitem_ParaRun_Lang              = window['AscDFH'].historyitem_type_ParaRun | 20;
	window['AscDFH'].historyitem_ParaRun_RFonts_Ascii      = window['AscDFH'].historyitem_type_ParaRun | 21;
	window['AscDFH'].historyitem_ParaRun_RFonts_HAnsi      = window['AscDFH'].historyitem_type_ParaRun | 22;
	window['AscDFH'].historyitem_ParaRun_RFonts_CS         = window['AscDFH'].historyitem_type_ParaRun | 23;
	window['AscDFH'].historyitem_ParaRun_RFonts_EastAsia   = window['AscDFH'].historyitem_type_ParaRun | 24;
	window['AscDFH'].historyitem_ParaRun_RFonts_Hint       = window['AscDFH'].historyitem_type_ParaRun | 25;
	window['AscDFH'].historyitem_ParaRun_Lang_Bidi         = window['AscDFH'].historyitem_type_ParaRun | 26;
	window['AscDFH'].historyitem_ParaRun_Lang_EastAsia     = window['AscDFH'].historyitem_type_ParaRun | 27;
	window['AscDFH'].historyitem_ParaRun_Lang_Val          = window['AscDFH'].historyitem_type_ParaRun | 28;
	window['AscDFH'].historyitem_ParaRun_TextPr            = window['AscDFH'].historyitem_type_ParaRun | 29;
	window['AscDFH'].historyitem_ParaRun_Unifill           = window['AscDFH'].historyitem_type_ParaRun | 30;
	window['AscDFH'].historyitem_ParaRun_Shd               = window['AscDFH'].historyitem_type_ParaRun | 31;
	window['AscDFH'].historyitem_ParaRun_MathStyle         = window['AscDFH'].historyitem_type_ParaRun | 32;
	window['AscDFH'].historyitem_ParaRun_MathPrp           = window['AscDFH'].historyitem_type_ParaRun | 33;
	window['AscDFH'].historyitem_ParaRun_ReviewType        = window['AscDFH'].historyitem_type_ParaRun | 34;
	window['AscDFH'].historyitem_ParaRun_PrChange          = window['AscDFH'].historyitem_type_ParaRun | 35;
	window['AscDFH'].historyitem_ParaRun_TextFill          = window['AscDFH'].historyitem_type_ParaRun | 36;
	window['AscDFH'].historyitem_ParaRun_TextOutline       = window['AscDFH'].historyitem_type_ParaRun | 37;
	window['AscDFH'].historyitem_ParaRun_PrReviewInfo      = window['AscDFH'].historyitem_type_ParaRun | 38;
	window['AscDFH'].historyitem_ParaRun_ContentReviewInfo = window['AscDFH'].historyitem_type_ParaRun | 39;
	window['AscDFH'].historyitem_ParaRun_OnStartSplit      = window['AscDFH'].historyitem_type_ParaRun | 40;
	window['AscDFH'].historyitem_ParaRun_OnEndSplit        = window['AscDFH'].historyitem_type_ParaRun | 41;
	window['AscDFH'].historyitem_ParaRun_MathAlnAt         = window['AscDFH'].historyitem_type_ParaRun | 42;
	window['AscDFH'].historyitem_ParaRun_MathForcedBreak   = window['AscDFH'].historyitem_type_ParaRun | 43;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CSectionPr
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Section_PageSize_Orient     = window['AscDFH'].historyitem_type_Section | 1;
	window['AscDFH'].historyitem_Section_PageSize_Size       = window['AscDFH'].historyitem_type_Section | 2;
	window['AscDFH'].historyitem_Section_PageMargins         = window['AscDFH'].historyitem_type_Section | 3;
	window['AscDFH'].historyitem_Section_Type                = window['AscDFH'].historyitem_type_Section | 4;
	window['AscDFH'].historyitem_Section_Borders_Left        = window['AscDFH'].historyitem_type_Section | 5;
	window['AscDFH'].historyitem_Section_Borders_Top         = window['AscDFH'].historyitem_type_Section | 6;
	window['AscDFH'].historyitem_Section_Borders_Right       = window['AscDFH'].historyitem_type_Section | 7;
	window['AscDFH'].historyitem_Section_Borders_Bottom      = window['AscDFH'].historyitem_type_Section | 8;
	window['AscDFH'].historyitem_Section_Borders_Display     = window['AscDFH'].historyitem_type_Section | 9;
	window['AscDFH'].historyitem_Section_Borders_OffsetFrom  = window['AscDFH'].historyitem_type_Section | 10;
	window['AscDFH'].historyitem_Section_Borders_ZOrder      = window['AscDFH'].historyitem_type_Section | 11;
	window['AscDFH'].historyitem_Section_Header_First        = window['AscDFH'].historyitem_type_Section | 12;
	window['AscDFH'].historyitem_Section_Header_Even         = window['AscDFH'].historyitem_type_Section | 13;
	window['AscDFH'].historyitem_Section_Header_Default      = window['AscDFH'].historyitem_type_Section | 14;
	window['AscDFH'].historyitem_Section_Footer_First        = window['AscDFH'].historyitem_type_Section | 15;
	window['AscDFH'].historyitem_Section_Footer_Even         = window['AscDFH'].historyitem_type_Section | 16;
	window['AscDFH'].historyitem_Section_Footer_Default      = window['AscDFH'].historyitem_type_Section | 17;
	window['AscDFH'].historyitem_Section_TitlePage           = window['AscDFH'].historyitem_type_Section | 18;
	window['AscDFH'].historyitem_Section_PageMargins_Header  = window['AscDFH'].historyitem_type_Section | 19;
	window['AscDFH'].historyitem_Section_PageMargins_Footer  = window['AscDFH'].historyitem_type_Section | 20;
	window['AscDFH'].historyitem_Section_PageNumType_Start   = window['AscDFH'].historyitem_type_Section | 21;
	window['AscDFH'].historyitem_Section_Columns_EqualWidth  = window['AscDFH'].historyitem_type_Section | 22;
	window['AscDFH'].historyitem_Section_Columns_Space       = window['AscDFH'].historyitem_type_Section | 23;
	window['AscDFH'].historyitem_Section_Columns_Num         = window['AscDFH'].historyitem_type_Section | 24;
	window['AscDFH'].historyitem_Section_Columns_Sep         = window['AscDFH'].historyitem_type_Section | 25;
	window['AscDFH'].historyitem_Section_Columns_Col         = window['AscDFH'].historyitem_type_Section | 26;
	window['AscDFH'].historyitem_Section_Columns_SetCols     = window['AscDFH'].historyitem_type_Section | 27;
	window['AscDFH'].historyitem_Section_Footnote_Pos        = window['AscDFH'].historyitem_type_Section | 28;
	window['AscDFH'].historyitem_Section_Footnote_NumStart   = window['AscDFH'].historyitem_type_Section | 29;
	window['AscDFH'].historyitem_Section_Footnote_NumRestart = window['AscDFH'].historyitem_type_Section | 30;
	window['AscDFH'].historyitem_Section_Footnote_NumFormat  = window['AscDFH'].historyitem_type_Section | 31;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaComment
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_ParaComment_CommentId = window['AscDFH'].historyitem_type_ParaComment | 1;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе ParaField
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Field_AddItem              = window['AscDFH'].historyitem_type_Field | 1;
	window['AscDFH'].historyitem_Field_RemoveItem           = window['AscDFH'].historyitem_type_Field | 2;
	window['AscDFH'].historyitem_Field_FormFieldName        = window['AscDFH'].historyitem_type_Field | 3;
	window['AscDFH'].historyitem_Field_FormFieldDefaultText = window['AscDFH'].historyitem_type_Field | 4;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе Footnotes
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Footnotes_AddFootnote              = window['AscDFH'].historyitem_type_Footnotes | 1;
	window['AscDFH'].historyitem_Footnotes_SetSeparator             = window['AscDFH'].historyitem_type_Footnotes | 2;
	window['AscDFH'].historyitem_Footnotes_SetContinuationSeparator = window['AscDFH'].historyitem_type_Footnotes | 3;
	window['AscDFH'].historyitem_Footnotes_SetContinuationNotice    = window['AscDFH'].historyitem_type_Footnotes | 4;
	window['AscDFH'].historyitem_Footnotes_SetFootnotePrPos         = window['AscDFH'].historyitem_type_Footnotes | 5;
	window['AscDFH'].historyitem_Footnotes_SetFootnotePrNumStart    = window['AscDFH'].historyitem_type_Footnotes | 6;
	window['AscDFH'].historyitem_Footnotes_SetFootnotePrNumRestart  = window['AscDFH'].historyitem_type_Footnotes | 7;
	window['AscDFH'].historyitem_Footnotes_SetFootnotePrNumFormat   = window['AscDFH'].historyitem_type_Footnotes | 8;
	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений в классе CSdtPr
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_SdtPr_Alias      = window['AscDFH'].historyitem_type_SdtPr | 1;
	window['AscDFH'].historyitem_SdtPr_Id         = window['AscDFH'].historyitem_type_SdtPr | 2;
	window['AscDFH'].historyitem_SdtPr_Tag        = window['AscDFH'].historyitem_type_SdtPr | 3;
	window['AscDFH'].historyitem_SdtPr_Label      = window['AscDFH'].historyitem_type_SdtPr | 4;
	window['AscDFH'].historyitem_SdtPr_Lock       = window['AscDFH'].historyitem_type_SdtPr | 5;
	window['AscDFH'].historyitem_SdtPr_DocPartObj = window['AscDFH'].historyitem_type_SdtPr | 6;
	window['AscDFH'].historyitem_SdtPr_Appearance = window['AscDFH'].historyitem_type_SdtPr | 7;
	window['AscDFH'].historyitem_SdtPr_Color      = window['AscDFH'].historyitem_type_SdtPr | 8;
	//------------------------------------------------------------------------------------------------------------------
	// Графические классы общего назначение (без привязки к конкретному классу)
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_AutoShapes_SetDrawingBaseCoors      = window['AscDFH'].historyitem_type_CommonShape | 101;
	window['AscDFH'].historyitem_AutoShapes_SetWorksheet             = window['AscDFH'].historyitem_type_CommonShape | 102;
	window['AscDFH'].historyitem_AutoShapes_AddToDrawingObjects      = window['AscDFH'].historyitem_type_CommonShape | 103;
	window['AscDFH'].historyitem_AutoShapes_RemoveFromDrawingObjects = window['AscDFH'].historyitem_type_CommonShape | 104;
	window['AscDFH'].historyitem_AutoShapes_SetBFromSerialize        = window['AscDFH'].historyitem_type_CommonShape | 105;
	window['AscDFH'].historyitem_AutoShapes_SetLocks                 = window['AscDFH'].historyitem_type_CommonShape | 106;
	window['AscDFH'].historyitem_AutoShapes_SetDrawingBaseType       = window['AscDFH'].historyitem_type_CommonShape | 107;
	window['AscDFH'].historyitem_AutoShapes_SetDrawingBaseExt        = window['AscDFH'].historyitem_type_CommonShape | 108;
	window['AscDFH'].historyitem_AutoShapes_SetDrawingBasePos        = window['AscDFH'].historyitem_type_CommonShape | 109;

	window['AscDFH'].historyitem_ChartFormatSetChart = window['AscDFH'].historyitem_type_CommonShape | 201;

	window['AscDFH'].historyitem_CommonChart_RemoveSeries    = window['AscDFH'].historyitem_type_CommonShape | 301;
	window['AscDFH'].historyitem_CommonSeries_RemoveDPt      = window['AscDFH'].historyitem_type_CommonShape | 302;
	window['AscDFH'].historyitem_CommonLit_RemoveDPt         = window['AscDFH'].historyitem_type_CommonShape | 303;
	window['AscDFH'].historyitem_CommonChartFormat_SetParent = window['AscDFH'].historyitem_type_CommonShape | 304;

	window['AscDFH'].historyitem_Common_AddWatermark = window['AscDFH'].historyitem_type_CommonShape | 401;
	//------------------------------------------------------------------------------------------------------------------
	// Графические классы
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_Presentation_AddSlide            = window['AscDFH'].historyitem_type_Presentation | 1;
	window['AscDFH'].historyitem_Presentation_RemoveSlide         = window['AscDFH'].historyitem_type_Presentation | 2;
	window['AscDFH'].historyitem_Presentation_SlideSize           = window['AscDFH'].historyitem_type_Presentation | 3;
	window['AscDFH'].historyitem_Presentation_AddSlideMaster      = window['AscDFH'].historyitem_type_Presentation | 4;
	window['AscDFH'].historyitem_Presentation_ChangeTheme         = window['AscDFH'].historyitem_type_Presentation | 5;
	window['AscDFH'].historyitem_Presentation_ChangeColorScheme   = window['AscDFH'].historyitem_type_Presentation | 6;
	window['AscDFH'].historyitem_Presentation_SetShowPr           = window['AscDFH'].historyitem_type_Presentation | 7;
	window['AscDFH'].historyitem_Presentation_SetDefaultTextStyle = window['AscDFH'].historyitem_type_Presentation | 8;
	window['AscDFH'].historyitem_Presentation_AddSection          = window['AscDFH'].historyitem_type_Presentation | 9;
	window['AscDFH'].historyitem_Presentation_RemoveSection       = window['AscDFH'].historyitem_type_Presentation | 10;

	window['AscDFH'].historyitem_ColorMod_SetName = window['AscDFH'].historyitem_type_ColorMod | 1;
	window['AscDFH'].historyitem_ColorMod_SetVal  = window['AscDFH'].historyitem_type_ColorMod | 2;

	window['AscDFH'].historyitem_ColorModifiers_AddColorMod    = window['AscDFH'].historyitem_type_ColorModifiers | 1;
	window['AscDFH'].historyitem_ColorModifiers_RemoveColorMod = window['AscDFH'].historyitem_type_ColorModifiers | 2;

	window['AscDFH'].historyitem_SysColor_SetId = window['AscDFH'].historyitem_type_SysColor | 1;
	window['AscDFH'].historyitem_SysColor_SetR  = window['AscDFH'].historyitem_type_SysColor | 2;
	window['AscDFH'].historyitem_SysColor_SetG  = window['AscDFH'].historyitem_type_SysColor | 3;
	window['AscDFH'].historyitem_SysColor_SetB  = window['AscDFH'].historyitem_type_SysColor | 4;

	window['AscDFH'].historyitem_PrstColor_SetId = window['AscDFH'].historyitem_type_PrstColor | 1;

	window['AscDFH'].historyitem_RGBColor_SetColor = window['AscDFH'].historyitem_type_RGBColor | 1;

	window['AscDFH'].historyitem_SchemeColor_SetId = window['AscDFH'].historyitem_type_SchemeColor | 1;

	window['AscDFH'].historyitem_UniColor_SetColor = window['AscDFH'].historyitem_type_UniColor | 1;
	window['AscDFH'].historyitem_UniColor_SetMods  = window['AscDFH'].historyitem_type_UniColor | 2;

	window['AscDFH'].historyitem_SrcRect_SetLTRB = window['AscDFH'].historyitem_type_SrcRect | 1;

	window['AscDFH'].historyitem_BlipFill_SetRasterImageId  = window['AscDFH'].historyitem_type_BlipFill | 1;
	window['AscDFH'].historyitem_BlipFill_SetVectorImageBin = window['AscDFH'].historyitem_type_BlipFill | 2;
	window['AscDFH'].historyitem_BlipFill_SetSrcRect        = window['AscDFH'].historyitem_type_BlipFill | 3;
	window['AscDFH'].historyitem_BlipFill_SetStretch        = window['AscDFH'].historyitem_type_BlipFill | 4;
	window['AscDFH'].historyitem_BlipFill_SetTile           = window['AscDFH'].historyitem_type_BlipFill | 5;
	window['AscDFH'].historyitem_BlipFill_SetRotWithShape   = window['AscDFH'].historyitem_type_BlipFill | 6;

	window['AscDFH'].historyitem_SolidFill_SetColor = window['AscDFH'].historyitem_type_SolidFill | 1;

	window['AscDFH'].historyitem_Gs_SetColor = window['AscDFH'].historyitem_type_Gs | 1;
	window['AscDFH'].historyitem_Gs_SetPos   = window['AscDFH'].historyitem_type_Gs | 2;

	window['AscDFH'].historyitem_GradLin_SetAngle = window['AscDFH'].historyitem_type_GradLin | 1;
	window['AscDFH'].historyitem_GradLin_SetScale = window['AscDFH'].historyitem_type_GradLin | 2;

	window['AscDFH'].historyitem_GradPath_SetPath = window['AscDFH'].historyitem_type_GradPath | 1;
	window['AscDFH'].historyitem_GradPath_SetRect = window['AscDFH'].historyitem_type_GradPath | 2;

	window['AscDFH'].historyitem_GradFill_AddColor = window['AscDFH'].historyitem_type_GradFill | 1;
	window['AscDFH'].historyitem_GradFill_SetLin   = window['AscDFH'].historyitem_type_GradFill | 2;
	window['AscDFH'].historyitem_GradFill_SetPath  = window['AscDFH'].historyitem_type_GradFill | 3;

	window['AscDFH'].historyitem_PathFill_SetFType = window['AscDFH'].historyitem_type_PathFill | 1;
	window['AscDFH'].historyitem_PathFill_SetFgClr = window['AscDFH'].historyitem_type_PathFill | 2;
	window['AscDFH'].historyitem_PathFill_SetBgClr = window['AscDFH'].historyitem_type_PathFill | 3;

	window['AscDFH'].historyitem_UniFill_SetFill        = window['AscDFH'].historyitem_type_UniFill | 1;
	window['AscDFH'].historyitem_UniFill_SetTransparent = window['AscDFH'].historyitem_type_UniFill | 2;

	window['AscDFH'].historyitem_EndArrow_SetType = window['AscDFH'].historyitem_type_EndArrow | 1;
	window['AscDFH'].historyitem_EndArrow_SetLen  = window['AscDFH'].historyitem_type_EndArrow | 2;
	window['AscDFH'].historyitem_EndArrow_SetW    = window['AscDFH'].historyitem_type_EndArrow | 3;

	window['AscDFH'].historyitem_LineJoin_SetType  = window['AscDFH'].historyitem_type_LineJoin | 1;
	window['AscDFH'].historyitem_LineJoin_SetLimit = window['AscDFH'].historyitem_type_LineJoin | 2;

	window['AscDFH'].historyitem_Ln_SetFill     = window['AscDFH'].historyitem_type_Ln | 1;
	window['AscDFH'].historyitem_Ln_SetPrstDash = window['AscDFH'].historyitem_type_Ln | 2;
	window['AscDFH'].historyitem_Ln_SetJoin     = window['AscDFH'].historyitem_type_Ln | 3;
	window['AscDFH'].historyitem_Ln_SetHeadEnd  = window['AscDFH'].historyitem_type_Ln | 4;
	window['AscDFH'].historyitem_Ln_SetTailEnd  = window['AscDFH'].historyitem_type_Ln | 5;
	window['AscDFH'].historyitem_Ln_SetAlgn     = window['AscDFH'].historyitem_type_Ln | 6;
	window['AscDFH'].historyitem_Ln_SetCap      = window['AscDFH'].historyitem_type_Ln | 7;
	window['AscDFH'].historyitem_Ln_SetCmpd     = window['AscDFH'].historyitem_type_Ln | 8;
	window['AscDFH'].historyitem_Ln_SetW        = window['AscDFH'].historyitem_type_Ln | 9;

	window['AscDFH'].historyitem_DefaultShapeDefinition_SetSpPr     = window['AscDFH'].historyitem_type_DefaultShapeDefinition | 1;
	window['AscDFH'].historyitem_DefaultShapeDefinition_SetBodyPr   = window['AscDFH'].historyitem_type_DefaultShapeDefinition | 2;
	window['AscDFH'].historyitem_DefaultShapeDefinition_SetLstStyle = window['AscDFH'].historyitem_type_DefaultShapeDefinition | 3;
	window['AscDFH'].historyitem_DefaultShapeDefinition_SetStyle    = window['AscDFH'].historyitem_type_DefaultShapeDefinition | 4;

	window['AscDFH'].historyitem_CNvPr_SetId         = window['AscDFH'].historyitem_type_CNvPr | 1;
	window['AscDFH'].historyitem_CNvPr_SetName       = window['AscDFH'].historyitem_type_CNvPr | 2;
	window['AscDFH'].historyitem_CNvPr_SetIsHidden   = window['AscDFH'].historyitem_type_CNvPr | 3;
	window['AscDFH'].historyitem_CNvPr_SetDescr      = window['AscDFH'].historyitem_type_CNvPr | 4;
	window['AscDFH'].historyitem_CNvPr_SetTitle      = window['AscDFH'].historyitem_type_CNvPr | 5;
	window['AscDFH'].historyitem_CNvPr_SetHlinkClick = window['AscDFH'].historyitem_type_CNvPr | 6;
	window['AscDFH'].historyitem_CNvPr_SetHlinkHover = window['AscDFH'].historyitem_type_CNvPr | 7;

	window['AscDFH'].historyitem_NvPr_SetIsPhoto   = window['AscDFH'].historyitem_type_NvPr | 1;
	window['AscDFH'].historyitem_NvPr_SetUserDrawn = window['AscDFH'].historyitem_type_NvPr | 2;
	window['AscDFH'].historyitem_NvPr_SetPh        = window['AscDFH'].historyitem_type_NvPr | 3;
	window['AscDFH'].historyitem_NvPr_SetUniMedia  = window['AscDFH'].historyitem_type_NvPr | 4;

	window['AscDFH'].historyitem_Ph_SetHasCustomPrompt = window['AscDFH'].historyitem_type_Ph | 1;
	window['AscDFH'].historyitem_Ph_SetIdx             = window['AscDFH'].historyitem_type_Ph | 2;
	window['AscDFH'].historyitem_Ph_SetOrient          = window['AscDFH'].historyitem_type_Ph | 3;
	window['AscDFH'].historyitem_Ph_SetSz              = window['AscDFH'].historyitem_type_Ph | 4;
	window['AscDFH'].historyitem_Ph_SetType            = window['AscDFH'].historyitem_type_Ph | 5;

	window['AscDFH'].historyitem_UniNvPr_SetCNvPr    = window['AscDFH'].historyitem_type_UniNvPr | 1;
	window['AscDFH'].historyitem_UniNvPr_SetUniPr    = window['AscDFH'].historyitem_type_UniNvPr | 2;
	window['AscDFH'].historyitem_UniNvPr_SetNvPr     = window['AscDFH'].historyitem_type_UniNvPr | 3;
	window['AscDFH'].historyitem_UniNvPr_SetUniSpPr  = window['AscDFH'].historyitem_type_UniNvPr | 4;

	window['AscDFH'].historyitem_StyleRef_SetIdx   = window['AscDFH'].historyitem_type_StyleRef | 1;
	window['AscDFH'].historyitem_StyleRef_SetColor = window['AscDFH'].historyitem_type_StyleRef | 2;

	window['AscDFH'].historyitem_FontRef_SetIdx   = window['AscDFH'].historyitem_type_FontRef | 1;
	window['AscDFH'].historyitem_FontRef_SetColor = window['AscDFH'].historyitem_type_FontRef | 2;

	window['AscDFH'].historyitem_Chart_SetAutoTitleDeleted = window['AscDFH'].historyitem_type_Chart | 1;
	window['AscDFH'].historyitem_Chart_SetBackWall         = window['AscDFH'].historyitem_type_Chart | 2;
	window['AscDFH'].historyitem_Chart_SetDispBlanksAs     = window['AscDFH'].historyitem_type_Chart | 3;
	window['AscDFH'].historyitem_Chart_SetFloor            = window['AscDFH'].historyitem_type_Chart | 4;
	window['AscDFH'].historyitem_Chart_SetLegend           = window['AscDFH'].historyitem_type_Chart | 5;
	window['AscDFH'].historyitem_Chart_AddPivotFmt         = window['AscDFH'].historyitem_type_Chart | 6;
	window['AscDFH'].historyitem_Chart_SetPlotArea         = window['AscDFH'].historyitem_type_Chart | 7;
	window['AscDFH'].historyitem_Chart_SetPlotVisOnly      = window['AscDFH'].historyitem_type_Chart | 8;
	window['AscDFH'].historyitem_Chart_SetShowDLblsOverMax = window['AscDFH'].historyitem_type_Chart | 9;
	window['AscDFH'].historyitem_Chart_SetSideWall         = window['AscDFH'].historyitem_type_Chart | 10;
	window['AscDFH'].historyitem_Chart_SetTitle            = window['AscDFH'].historyitem_type_Chart | 11;
	window['AscDFH'].historyitem_Chart_SetView3D           = window['AscDFH'].historyitem_type_Chart | 12;

	window['AscDFH'].historyitem_ChartSpace_SetChart          = window['AscDFH'].historyitem_type_ChartSpace | 1;
	window['AscDFH'].historyitem_ChartSpace_SetClrMapOvr      = window['AscDFH'].historyitem_type_ChartSpace | 2;
	window['AscDFH'].historyitem_ChartSpace_SetDate1904       = window['AscDFH'].historyitem_type_ChartSpace | 3;
	window['AscDFH'].historyitem_ChartSpace_SetExternalData   = window['AscDFH'].historyitem_type_ChartSpace | 4;
	window['AscDFH'].historyitem_ChartSpace_SetLang           = window['AscDFH'].historyitem_type_ChartSpace | 5;
	window['AscDFH'].historyitem_ChartSpace_SetPivotSource    = window['AscDFH'].historyitem_type_ChartSpace | 6;
	window['AscDFH'].historyitem_ChartSpace_SetPrintSettings  = window['AscDFH'].historyitem_type_ChartSpace | 7;
	window['AscDFH'].historyitem_ChartSpace_SetProtection     = window['AscDFH'].historyitem_type_ChartSpace | 8;
	window['AscDFH'].historyitem_ChartSpace_SetRoundedCorners = window['AscDFH'].historyitem_type_ChartSpace | 9;
	window['AscDFH'].historyitem_ChartSpace_SetSpPr           = window['AscDFH'].historyitem_type_ChartSpace | 10;
	window['AscDFH'].historyitem_ChartSpace_SetStyle          = window['AscDFH'].historyitem_type_ChartSpace | 11;
	window['AscDFH'].historyitem_ChartSpace_SetTxPr           = window['AscDFH'].historyitem_type_ChartSpace | 12;
	window['AscDFH'].historyitem_ChartSpace_SetUserShapes     = window['AscDFH'].historyitem_type_ChartSpace | 13;
	window['AscDFH'].historyitem_ChartSpace_SetThemeOverride  = window['AscDFH'].historyitem_type_ChartSpace | 14;
	window['AscDFH'].historyitem_ChartSpace_SetGroup          = window['AscDFH'].historyitem_type_ChartSpace | 15;
	window['AscDFH'].historyitem_ChartSpace_SetParent         = window['AscDFH'].historyitem_type_ChartSpace | 16;
	window['AscDFH'].historyitem_ChartSpace_SetNvGrFrProps    = window['AscDFH'].historyitem_type_ChartSpace | 17;

	window['AscDFH'].historyitem_Legend_SetLayout      = window['AscDFH'].historyitem_type_Legend | 1;
	window['AscDFH'].historyitem_Legend_AddLegendEntry = window['AscDFH'].historyitem_type_Legend | 2;
	window['AscDFH'].historyitem_Legend_SetLegendPos   = window['AscDFH'].historyitem_type_Legend | 3;
	window['AscDFH'].historyitem_Legend_SetOverlay     = window['AscDFH'].historyitem_type_Legend | 4;
	window['AscDFH'].historyitem_Legend_SetSpPr        = window['AscDFH'].historyitem_type_Legend | 5;
	window['AscDFH'].historyitem_Legend_SetTxPr        = window['AscDFH'].historyitem_type_Legend | 6;

	window['AscDFH'].historyitem_Layout_SetH            = window['AscDFH'].historyitem_type_Layout | 1;
	window['AscDFH'].historyitem_Layout_SetHMode        = window['AscDFH'].historyitem_type_Layout | 2;
	window['AscDFH'].historyitem_Layout_SetLayoutTarget = window['AscDFH'].historyitem_type_Layout | 3;
	window['AscDFH'].historyitem_Layout_SetW            = window['AscDFH'].historyitem_type_Layout | 4;
	window['AscDFH'].historyitem_Layout_SetWMode        = window['AscDFH'].historyitem_type_Layout | 5;
	window['AscDFH'].historyitem_Layout_SetX            = window['AscDFH'].historyitem_type_Layout | 6;
	window['AscDFH'].historyitem_Layout_SetXMode        = window['AscDFH'].historyitem_type_Layout | 7;
	window['AscDFH'].historyitem_Layout_SetY            = window['AscDFH'].historyitem_type_Layout | 8;
	window['AscDFH'].historyitem_Layout_SetYMode        = window['AscDFH'].historyitem_type_Layout | 9;

	window['AscDFH'].historyitem_LegendEntry_SetDelete = window['AscDFH'].historyitem_type_LegendEntry | 1;
	window['AscDFH'].historyitem_LegendEntry_SetIdx    = window['AscDFH'].historyitem_type_LegendEntry | 2;
	window['AscDFH'].historyitem_LegendEntry_SetTxPr   = window['AscDFH'].historyitem_type_LegendEntry | 3;

	window['AscDFH'].historyitem_PivotFmt_SetDLbl   = window['AscDFH'].historyitem_type_PivotFmt | 1;
	window['AscDFH'].historyitem_PivotFmt_SetIdx    = window['AscDFH'].historyitem_type_PivotFmt | 2;
	window['AscDFH'].historyitem_PivotFmt_SetMarker = window['AscDFH'].historyitem_type_PivotFmt | 3;
	window['AscDFH'].historyitem_PivotFmt_SetSpPr   = window['AscDFH'].historyitem_type_PivotFmt | 4;
	window['AscDFH'].historyitem_PivotFmt_SetTxPr   = window['AscDFH'].historyitem_type_PivotFmt | 5;

	window['AscDFH'].historyitem_DLbl_SetDelete         = window['AscDFH'].historyitem_type_DLbl | 1;
	window['AscDFH'].historyitem_DLbl_SetDLblPos        = window['AscDFH'].historyitem_type_DLbl | 2;
	window['AscDFH'].historyitem_DLbl_SetIdx            = window['AscDFH'].historyitem_type_DLbl | 3;
	window['AscDFH'].historyitem_DLbl_SetLayout         = window['AscDFH'].historyitem_type_DLbl | 4;
	window['AscDFH'].historyitem_DLbl_SetNumFmt         = window['AscDFH'].historyitem_type_DLbl | 5;
	window['AscDFH'].historyitem_DLbl_SetSeparator      = window['AscDFH'].historyitem_type_DLbl | 6;
	window['AscDFH'].historyitem_DLbl_SetShowBubbleSize = window['AscDFH'].historyitem_type_DLbl | 7;
	window['AscDFH'].historyitem_DLbl_SetShowCatName    = window['AscDFH'].historyitem_type_DLbl | 8;
	window['AscDFH'].historyitem_DLbl_SetShowLegendKey  = window['AscDFH'].historyitem_type_DLbl | 9;
	window['AscDFH'].historyitem_DLbl_SetShowPercent    = window['AscDFH'].historyitem_type_DLbl | 10;
	window['AscDFH'].historyitem_DLbl_SetShowSerName    = window['AscDFH'].historyitem_type_DLbl | 11;
	window['AscDFH'].historyitem_DLbl_SetShowVal        = window['AscDFH'].historyitem_type_DLbl | 12;
	window['AscDFH'].historyitem_DLbl_SetSpPr           = window['AscDFH'].historyitem_type_DLbl | 13;
	window['AscDFH'].historyitem_DLbl_SetTx             = window['AscDFH'].historyitem_type_DLbl | 14;
	window['AscDFH'].historyitem_DLbl_SetTxPr           = window['AscDFH'].historyitem_type_DLbl | 15;

	window['AscDFH'].historyitem_Marker_SetSize   = window['AscDFH'].historyitem_type_Marker | 1;
	window['AscDFH'].historyitem_Marker_SetSpPr   = window['AscDFH'].historyitem_type_Marker | 2;
	window['AscDFH'].historyitem_Marker_SetSymbol = window['AscDFH'].historyitem_type_Marker | 3;

	window['AscDFH'].historyitem_PlotArea_AddChart    = window['AscDFH'].historyitem_type_PlotArea | 1;
	window['AscDFH'].historyitem_PlotArea_SetCatAx    = window['AscDFH'].historyitem_type_PlotArea | 2;
	window['AscDFH'].historyitem_PlotArea_SetDateAx   = window['AscDFH'].historyitem_type_PlotArea | 3;
	window['AscDFH'].historyitem_PlotArea_SetDTable   = window['AscDFH'].historyitem_type_PlotArea | 4;
	window['AscDFH'].historyitem_PlotArea_SetLayout   = window['AscDFH'].historyitem_type_PlotArea | 5;
	window['AscDFH'].historyitem_PlotArea_SetSerAx    = window['AscDFH'].historyitem_type_PlotArea | 6;
	window['AscDFH'].historyitem_PlotArea_SetSpPr     = window['AscDFH'].historyitem_type_PlotArea | 7;
	window['AscDFH'].historyitem_PlotArea_SetValAx    = window['AscDFH'].historyitem_type_PlotArea | 8;
	window['AscDFH'].historyitem_PlotArea_AddAxis     = window['AscDFH'].historyitem_type_PlotArea | 9;
	window['AscDFH'].historyitem_PlotArea_RemoveChart = window['AscDFH'].historyitem_type_PlotArea | 10;
	window['AscDFH'].historyitem_PlotArea_RemoveAxis  = window['AscDFH'].historyitem_type_PlotArea | 11;

	window['AscDFH'].historyitem_NumFmt_SetFormatCode   = window['AscDFH'].historyitem_type_NumFmt | 1;
	window['AscDFH'].historyitem_NumFmt_SetSourceLinked = window['AscDFH'].historyitem_type_NumFmt | 2;

	window['AscDFH'].historyitem_Scaling_SetLogBase     = window['AscDFH'].historyitem_type_Scaling | 1;
	window['AscDFH'].historyitem_Scaling_SetMax         = window['AscDFH'].historyitem_type_Scaling | 2;
	window['AscDFH'].historyitem_Scaling_SetMin         = window['AscDFH'].historyitem_type_Scaling | 3;
	window['AscDFH'].historyitem_Scaling_SetOrientation = window['AscDFH'].historyitem_type_Scaling | 4;
	window['AscDFH'].historyitem_Scaling_SetParent      = window['AscDFH'].historyitem_type_Scaling | 5;

	window['AscDFH'].historyitem_DTable_SetShowHorzBorder = window['AscDFH'].historyitem_type_DTable | 1;
	window['AscDFH'].historyitem_DTable_SetShowKeys       = window['AscDFH'].historyitem_type_DTable | 2;
	window['AscDFH'].historyitem_DTable_SetShowOutline    = window['AscDFH'].historyitem_type_DTable | 3;
	window['AscDFH'].historyitem_DTable_SetShowVertBorder = window['AscDFH'].historyitem_type_DTable | 4;
	window['AscDFH'].historyitem_DTable_SetSpPr           = window['AscDFH'].historyitem_type_DTable | 5;
	window['AscDFH'].historyitem_DTable_SetTxPr           = window['AscDFH'].historyitem_type_DTable | 6;

	window['AscDFH'].historyitem_LineChart_AddAxId       = window['AscDFH'].historyitem_type_LineChart | 1;
	window['AscDFH'].historyitem_LineChart_SetDLbls      = window['AscDFH'].historyitem_type_LineChart | 2;
	window['AscDFH'].historyitem_LineChart_SetDropLines  = window['AscDFH'].historyitem_type_LineChart | 3;
	window['AscDFH'].historyitem_LineChart_SetGrouping   = window['AscDFH'].historyitem_type_LineChart | 4;
	window['AscDFH'].historyitem_LineChart_SetHiLowLines = window['AscDFH'].historyitem_type_LineChart | 5;
	window['AscDFH'].historyitem_LineChart_SetMarker     = window['AscDFH'].historyitem_type_LineChart | 6;
	window['AscDFH'].historyitem_LineChart_AddSer        = window['AscDFH'].historyitem_type_LineChart | 7;
	window['AscDFH'].historyitem_LineChart_SetSmooth     = window['AscDFH'].historyitem_type_LineChart | 8;
	window['AscDFH'].historyitem_LineChart_SetUpDownBars = window['AscDFH'].historyitem_type_LineChart | 9;
	window['AscDFH'].historyitem_LineChart_SetVaryColors = window['AscDFH'].historyitem_type_LineChart | 10;

	window['AscDFH'].historyitem_DLbls_SetDelete          = window['AscDFH'].historyitem_type_DLbls | 1;
	window['AscDFH'].historyitem_DLbls_SetDLbl            = window['AscDFH'].historyitem_type_DLbls | 2;
	window['AscDFH'].historyitem_DLbls_SetDLblPos         = window['AscDFH'].historyitem_type_DLbls | 3;
	window['AscDFH'].historyitem_DLbls_SetLeaderLines     = window['AscDFH'].historyitem_type_DLbls | 4;
	window['AscDFH'].historyitem_DLbls_SetNumFmt          = window['AscDFH'].historyitem_type_DLbls | 5;
	window['AscDFH'].historyitem_DLbls_SetSeparator       = window['AscDFH'].historyitem_type_DLbls | 6;
	window['AscDFH'].historyitem_DLbls_SetShowBubbleSize  = window['AscDFH'].historyitem_type_DLbls | 7;
	window['AscDFH'].historyitem_DLbls_SetShowCatName     = window['AscDFH'].historyitem_type_DLbls | 8;
	window['AscDFH'].historyitem_DLbls_SetShowLeaderLines = window['AscDFH'].historyitem_type_DLbls | 9;
	window['AscDFH'].historyitem_DLbls_SetShowLegendKey   = window['AscDFH'].historyitem_type_DLbls | 10;
	window['AscDFH'].historyitem_DLbls_SetShowPercent     = window['AscDFH'].historyitem_type_DLbls | 11;
	window['AscDFH'].historyitem_DLbls_SetShowSerName     = window['AscDFH'].historyitem_type_DLbls | 12;
	window['AscDFH'].historyitem_DLbls_SetShowVal         = window['AscDFH'].historyitem_type_DLbls | 13;
	window['AscDFH'].historyitem_DLbls_SetSpPr            = window['AscDFH'].historyitem_type_DLbls | 14;
	window['AscDFH'].historyitem_DLbls_SetTxPr            = window['AscDFH'].historyitem_type_DLbls | 15;

	window['AscDFH'].historyitem_UpDownBars_SetDownBars = window['AscDFH'].historyitem_type_UpDownBars | 1;
	window['AscDFH'].historyitem_UpDownBars_SetGapWidth = window['AscDFH'].historyitem_type_UpDownBars | 2;
	window['AscDFH'].historyitem_UpDownBars_SetUpBars   = window['AscDFH'].historyitem_type_UpDownBars | 3;

	window['AscDFH'].historyitem_BarChart_AddAxId       = window['AscDFH'].historyitem_type_BarChart | 1;
	window['AscDFH'].historyitem_BarChart_SetBarDir     = window['AscDFH'].historyitem_type_BarChart | 2;
	window['AscDFH'].historyitem_BarChart_SetDLbls      = window['AscDFH'].historyitem_type_BarChart | 3;
	window['AscDFH'].historyitem_BarChart_SetGapWidth   = window['AscDFH'].historyitem_type_BarChart | 4;
	window['AscDFH'].historyitem_BarChart_SetGrouping   = window['AscDFH'].historyitem_type_BarChart | 5;
	window['AscDFH'].historyitem_BarChart_SetOverlap    = window['AscDFH'].historyitem_type_BarChart | 6;
	window['AscDFH'].historyitem_BarChart_AddSer        = window['AscDFH'].historyitem_type_BarChart | 7;
	window['AscDFH'].historyitem_BarChart_SetSerLines   = window['AscDFH'].historyitem_type_BarChart | 8;
	window['AscDFH'].historyitem_BarChart_SetVaryColors = window['AscDFH'].historyitem_type_BarChart | 9;
	window['AscDFH'].historyitem_BarChart_Set3D         = window['AscDFH'].historyitem_type_BarChart | 10;
	window['AscDFH'].historyitem_BarChart_SetGapDepth   = window['AscDFH'].historyitem_type_BarChart | 11;
	window['AscDFH'].historyitem_BarChart_SetShape      = window['AscDFH'].historyitem_type_BarChart | 12;

	window['AscDFH'].historyitem_BubbleChart_AddAxId           = window['AscDFH'].historyitem_type_BubbleChart | 1;
	window['AscDFH'].historyitem_BubbleChart_SetBubble3D       = window['AscDFH'].historyitem_type_BubbleChart | 2;
	window['AscDFH'].historyitem_BubbleChart_SetBubbleScale    = window['AscDFH'].historyitem_type_BubbleChart | 3;
	window['AscDFH'].historyitem_BubbleChart_SetDLbls          = window['AscDFH'].historyitem_type_BubbleChart | 4;
	window['AscDFH'].historyitem_BubbleChart_AddSerie          = window['AscDFH'].historyitem_type_BubbleChart | 5;
	window['AscDFH'].historyitem_BubbleChart_SetShowNegBubbles = window['AscDFH'].historyitem_type_BubbleChart | 6;
	window['AscDFH'].historyitem_BubbleChart_SetSizeRepresents = window['AscDFH'].historyitem_type_BubbleChart | 7;
	window['AscDFH'].historyitem_BubbleChart_SetVaryColors     = window['AscDFH'].historyitem_type_BubbleChart | 8;

	window['AscDFH'].historyitem_DoughnutChart_SetDLbls         = window['AscDFH'].historyitem_type_DoughnutChart | 1;
	window['AscDFH'].historyitem_DoughnutChart_SetFirstSliceAng = window['AscDFH'].historyitem_type_DoughnutChart | 2;
	window['AscDFH'].historyitem_DoughnutChart_SetHoleSize      = window['AscDFH'].historyitem_type_DoughnutChart | 3;
	window['AscDFH'].historyitem_DoughnutChart_AddSer           = window['AscDFH'].historyitem_type_DoughnutChart | 4;
	window['AscDFH'].historyitem_DoughnutChart_SetVaryColor     = window['AscDFH'].historyitem_type_DoughnutChart | 5;

	window['AscDFH'].historyitem_OfPieChart_AddCustSplit     = window['AscDFH'].historyitem_type_OfPieChart | 1;
	window['AscDFH'].historyitem_OfPieChart_SetDLbls         = window['AscDFH'].historyitem_type_OfPieChart | 2;
	window['AscDFH'].historyitem_OfPieChart_SetGapWidth      = window['AscDFH'].historyitem_type_OfPieChart | 3;
	window['AscDFH'].historyitem_OfPieChart_SetOfPieType     = window['AscDFH'].historyitem_type_OfPieChart | 4;
	window['AscDFH'].historyitem_OfPieChart_SetSecondPieSize = window['AscDFH'].historyitem_type_OfPieChart | 5;
	window['AscDFH'].historyitem_OfPieChart_AddSer           = window['AscDFH'].historyitem_type_OfPieChart | 6;
	window['AscDFH'].historyitem_OfPieChart_SetSerLines      = window['AscDFH'].historyitem_type_OfPieChart | 7;
	window['AscDFH'].historyitem_OfPieChart_SetSplitPos      = window['AscDFH'].historyitem_type_OfPieChart | 8;
	window['AscDFH'].historyitem_OfPieChart_SetSplitType     = window['AscDFH'].historyitem_type_OfPieChart | 9;
	window['AscDFH'].historyitem_OfPieChart_SetVaryColors    = window['AscDFH'].historyitem_type_OfPieChart | 10;

	window['AscDFH'].historyitem_PieChart_SetDLbls         = window['AscDFH'].historyitem_type_PieChart | 1;
	window['AscDFH'].historyitem_PieChart_SetFirstSliceAng = window['AscDFH'].historyitem_type_PieChart | 2;
	window['AscDFH'].historyitem_PieChart_AddSer           = window['AscDFH'].historyitem_type_PieChart | 3;
	window['AscDFH'].historyitem_PieChart_SetVaryColors    = window['AscDFH'].historyitem_type_PieChart | 4;

	window['AscDFH'].historyitem_RadarChart_AddAxId       = window['AscDFH'].historyitem_type_RadarChart | 1;
	window['AscDFH'].historyitem_RadarChart_SetDLbls      = window['AscDFH'].historyitem_type_RadarChart | 2;
	window['AscDFH'].historyitem_RadarChart_SetRadarStyle = window['AscDFH'].historyitem_type_RadarChart | 3;
	window['AscDFH'].historyitem_RadarChart_AddSer        = window['AscDFH'].historyitem_type_RadarChart | 4;
	window['AscDFH'].historyitem_RadarChart_SetVaryColors = window['AscDFH'].historyitem_type_RadarChart | 5;

	window['AscDFH'].historyitem_ScatterChart_AddAxId         = window['AscDFH'].historyitem_type_ScatterChart | 1;
	window['AscDFH'].historyitem_ScatterChart_SetDLbls        = window['AscDFH'].historyitem_type_ScatterChart | 2;
	window['AscDFH'].historyitem_ScatterChart_SetScatterStyle = window['AscDFH'].historyitem_type_ScatterChart | 3;
	window['AscDFH'].historyitem_ScatterChart_AddSer          = window['AscDFH'].historyitem_type_ScatterChart | 4;
	window['AscDFH'].historyitem_ScatterChart_SetVaryColors   = window['AscDFH'].historyitem_type_ScatterChart | 5;

	window['AscDFH'].historyitem_StockChart_AddAxId       = window['AscDFH'].historyitem_type_StockChart | 1;
	window['AscDFH'].historyitem_StockChart_SetDLbls      = window['AscDFH'].historyitem_type_StockChart | 2;
	window['AscDFH'].historyitem_StockChart_SetDropLines  = window['AscDFH'].historyitem_type_StockChart | 3;
	window['AscDFH'].historyitem_StockChart_SetHiLowLines = window['AscDFH'].historyitem_type_StockChart | 4;
	window['AscDFH'].historyitem_StockChart_AddSer        = window['AscDFH'].historyitem_type_StockChart | 5;
	window['AscDFH'].historyitem_StockChart_SetUpDownBars = window['AscDFH'].historyitem_type_StockChart | 6;

	window['AscDFH'].historyitem_SurfaceChart_AddAxId      = window['AscDFH'].historyitem_type_SurfaceChart | 1;
	window['AscDFH'].historyitem_SurfaceChart_AddBandFmt   = window['AscDFH'].historyitem_type_SurfaceChart | 2;
	window['AscDFH'].historyitem_SurfaceChart_AddSer       = window['AscDFH'].historyitem_type_SurfaceChart | 3;
	window['AscDFH'].historyitem_SurfaceChart_SetWireframe = window['AscDFH'].historyitem_type_SurfaceChart | 4;

	window['AscDFH'].historyitem_BandFmt_SetIdx  = window['AscDFH'].historyitem_type_BandFmt | 1;
	window['AscDFH'].historyitem_BandFmt_SetSpPr = window['AscDFH'].historyitem_type_BandFmt | 2;

	window['AscDFH'].historyitem_AreaChart_AddAxId       = window['AscDFH'].historyitem_type_AreaChart | 1;
	window['AscDFH'].historyitem_AreaChart_SetDLbls      = window['AscDFH'].historyitem_type_AreaChart | 2;
	window['AscDFH'].historyitem_AreaChart_SetDropLines  = window['AscDFH'].historyitem_type_AreaChart | 3;
	window['AscDFH'].historyitem_AreaChart_SetGrouping   = window['AscDFH'].historyitem_type_AreaChart | 4;
	window['AscDFH'].historyitem_AreaChart_AddSer        = window['AscDFH'].historyitem_type_AreaChart | 5;
	window['AscDFH'].historyitem_AreaChart_SetVaryColors = window['AscDFH'].historyitem_type_AreaChart | 6;

	window['AscDFH'].historyitem_ScatterSer_SetDLbls     = window['AscDFH'].historyitem_type_ScatterSer | 1;
	window['AscDFH'].historyitem_ScatterSer_SetDPt       = window['AscDFH'].historyitem_type_ScatterSer | 2;
	window['AscDFH'].historyitem_ScatterSer_SetErrBars   = window['AscDFH'].historyitem_type_ScatterSer | 3;
	window['AscDFH'].historyitem_ScatterSer_SetIdx       = window['AscDFH'].historyitem_type_ScatterSer | 4;
	window['AscDFH'].historyitem_ScatterSer_SetMarker    = window['AscDFH'].historyitem_type_ScatterSer | 5;
	window['AscDFH'].historyitem_ScatterSer_SetOrder     = window['AscDFH'].historyitem_type_ScatterSer | 6;
	window['AscDFH'].historyitem_ScatterSer_SetSmooth    = window['AscDFH'].historyitem_type_ScatterSer | 7;
	window['AscDFH'].historyitem_ScatterSer_SetSpPr      = window['AscDFH'].historyitem_type_ScatterSer | 8;
	window['AscDFH'].historyitem_ScatterSer_SetTrendline = window['AscDFH'].historyitem_type_ScatterSer | 9;
	window['AscDFH'].historyitem_ScatterSer_SetTx        = window['AscDFH'].historyitem_type_ScatterSer | 10;
	window['AscDFH'].historyitem_ScatterSer_SetXVal      = window['AscDFH'].historyitem_type_ScatterSer | 11;
	window['AscDFH'].historyitem_ScatterSer_SetYVal      = window['AscDFH'].historyitem_type_ScatterSer | 12;

	window['AscDFH'].historyitem_DPt_SetBubble3D         = window['AscDFH'].historyitem_type_DPt | 1;
	window['AscDFH'].historyitem_DPt_SetExplosion        = window['AscDFH'].historyitem_type_DPt | 2;
	window['AscDFH'].historyitem_DPt_SetIdx              = window['AscDFH'].historyitem_type_DPt | 3;
	window['AscDFH'].historyitem_DPt_SetInvertIfNegative = window['AscDFH'].historyitem_type_DPt | 4;
	window['AscDFH'].historyitem_DPt_SetMarker           = window['AscDFH'].historyitem_type_DPt | 5;
	window['AscDFH'].historyitem_DPt_SetPictureOptions   = window['AscDFH'].historyitem_type_DPt | 6;
	window['AscDFH'].historyitem_DPt_SetSpPr             = window['AscDFH'].historyitem_type_DPt | 7;

	window['AscDFH'].historyitem_ErrBars_SetErrBarType = window['AscDFH'].historyitem_type_ErrBars | 1;
	window['AscDFH'].historyitem_ErrBars_SetErrDir     = window['AscDFH'].historyitem_type_ErrBars | 2;
	window['AscDFH'].historyitem_ErrBars_SetErrValType = window['AscDFH'].historyitem_type_ErrBars | 3;
	window['AscDFH'].historyitem_ErrBars_SetMinus      = window['AscDFH'].historyitem_type_ErrBars | 4;
	window['AscDFH'].historyitem_ErrBars_SetNoEndCap   = window['AscDFH'].historyitem_type_ErrBars | 5;
	window['AscDFH'].historyitem_ErrBars_SetPlus       = window['AscDFH'].historyitem_type_ErrBars | 6;
	window['AscDFH'].historyitem_ErrBars_SetSpPr       = window['AscDFH'].historyitem_type_ErrBars | 7;
	window['AscDFH'].historyitem_ErrBars_SetVal        = window['AscDFH'].historyitem_type_ErrBars | 8;

	window['AscDFH'].historyitem_MinusPlus_SetnNumLit = window['AscDFH'].historyitem_type_MinusPlus | 1;
	window['AscDFH'].historyitem_MinusPlus_SetnNumRef = window['AscDFH'].historyitem_type_MinusPlus | 2;

	window['AscDFH'].historyitem_NumLit_SetFormatCode = window['AscDFH'].historyitem_type_NumLit | 1;
	window['AscDFH'].historyitem_NumLit_AddPt         = window['AscDFH'].historyitem_type_NumLit | 2;
	window['AscDFH'].historyitem_NumLit_SetPtCount    = window['AscDFH'].historyitem_type_NumLit | 3;

	window['AscDFH'].historyitem_NumericPoint_SetFormatCode = window['AscDFH'].historyitem_type_NumericPoint | 1;
	window['AscDFH'].historyitem_NumericPoint_SetIdx        = window['AscDFH'].historyitem_type_NumericPoint | 2;
	window['AscDFH'].historyitem_NumericPoint_SetVal        = window['AscDFH'].historyitem_type_NumericPoint | 3;

	window['AscDFH'].historyitem_NumRef_SetF        = window['AscDFH'].historyitem_type_NumRef | 1;
	window['AscDFH'].historyitem_NumRef_SetNumCache = window['AscDFH'].historyitem_type_NumRef | 2;

	window['AscDFH'].historyitem_Trendline_SetBackward      = window['AscDFH'].historyitem_type_TrendLine | 1;
	window['AscDFH'].historyitem_Trendline_SetDispEq        = window['AscDFH'].historyitem_type_TrendLine | 2;
	window['AscDFH'].historyitem_Trendline_SetDispRSqr      = window['AscDFH'].historyitem_type_TrendLine | 3;
	window['AscDFH'].historyitem_Trendline_SetForward       = window['AscDFH'].historyitem_type_TrendLine | 4;
	window['AscDFH'].historyitem_Trendline_SetIntercept     = window['AscDFH'].historyitem_type_TrendLine | 5;
	window['AscDFH'].historyitem_Trendline_SetName          = window['AscDFH'].historyitem_type_TrendLine | 6;
	window['AscDFH'].historyitem_Trendline_SetOrder         = window['AscDFH'].historyitem_type_TrendLine | 7;
	window['AscDFH'].historyitem_Trendline_SetPeriod        = window['AscDFH'].historyitem_type_TrendLine | 8;
	window['AscDFH'].historyitem_Trendline_SetSpPr          = window['AscDFH'].historyitem_type_TrendLine | 9;
	window['AscDFH'].historyitem_Trendline_SetTrendlineLbl  = window['AscDFH'].historyitem_type_TrendLine | 10;
	window['AscDFH'].historyitem_Trendline_SetTrendlineType = window['AscDFH'].historyitem_type_TrendLine | 11;

	window['AscDFH'].historyitem_Tx_SetStrRef = window['AscDFH'].historyitem_type_Tx | 1;
	window['AscDFH'].historyitem_Tx_SetVal    = window['AscDFH'].historyitem_type_Tx | 2;

	window['AscDFH'].historyitem_StrRef_SetF        = window['AscDFH'].historyitem_type_StrRef | 1;
	window['AscDFH'].historyitem_StrRef_SetStrCache = window['AscDFH'].historyitem_type_StrRef | 2;

	window['AscDFH'].historyitem_StrCache_AddPt      = window['AscDFH'].historyitem_type_StrCache | 1;
	window['AscDFH'].historyitem_StrCache_SetPtCount = window['AscDFH'].historyitem_type_StrCache | 2;

	window['AscDFH'].historyitem_StrPoint_SetIdx = window['AscDFH'].historyitem_type_StrPoint | 1;
	window['AscDFH'].historyitem_StrPoint_SetVal = window['AscDFH'].historyitem_type_StrPoint | 2;

	window['AscDFH'].historyitem_XVal_SetMultiLvlStrRef = window['AscDFH'].historyitem_type_XVal | 1;
	window['AscDFH'].historyitem_XVal_SetNumLit         = window['AscDFH'].historyitem_type_XVal | 2;
	window['AscDFH'].historyitem_XVal_SetNumRef         = window['AscDFH'].historyitem_type_XVal | 3;
	window['AscDFH'].historyitem_XVal_SetStrLit         = window['AscDFH'].historyitem_type_XVal | 4;
	window['AscDFH'].historyitem_XVal_SetStrRef         = window['AscDFH'].historyitem_type_XVal | 5;

	window['AscDFH'].historyitem_MultiLvlStrRef_SetF                = window['AscDFH'].historyitem_type_MultiLvlStrRef | 1;
	window['AscDFH'].historyitem_MultiLvlStrRef_SetMultiLvlStrCache = window['AscDFH'].historyitem_type_MultiLvlStrRef | 2;

	window['AscDFH'].historyitem_MultiLvlStrCache_SetLvl     = window['AscDFH'].historyitem_type_MultiLvlStrCache | 1;
	window['AscDFH'].historyitem_MultiLvlStrCache_SetPtCount = window['AscDFH'].historyitem_type_MultiLvlStrCache | 2;

	window['AscDFH'].historyitem_StringLiteral_SetPt      = window['AscDFH'].historyitem_type_StringLiteral | 1;
	window['AscDFH'].historyitem_StringLiteral_SetPtCount = window['AscDFH'].historyitem_type_StringLiteral | 2;

	window['AscDFH'].historyitem_YVal_SetNumLit = window['AscDFH'].historyitem_type_YVal | 1;
	window['AscDFH'].historyitem_YVal_SetNumRef = window['AscDFH'].historyitem_type_YVal | 2;

	window['AscDFH'].historyitem_AreaSeries_SetCat            = window['AscDFH'].historyitem_type_AreaSeries | 1;
	window['AscDFH'].historyitem_AreaSeries_SetDLbls          = window['AscDFH'].historyitem_type_AreaSeries | 2;
	window['AscDFH'].historyitem_AreaSeries_SetDPt            = window['AscDFH'].historyitem_type_AreaSeries | 3;
	window['AscDFH'].historyitem_AreaSeries_SetErrBars        = window['AscDFH'].historyitem_type_AreaSeries | 4;
	window['AscDFH'].historyitem_AreaSeries_SetIdx            = window['AscDFH'].historyitem_type_AreaSeries | 5;
	window['AscDFH'].historyitem_AreaSeries_SetOrder          = window['AscDFH'].historyitem_type_AreaSeries | 6;
	window['AscDFH'].historyitem_AreaSeries_SetPictureOptions = window['AscDFH'].historyitem_type_AreaSeries | 7;
	window['AscDFH'].historyitem_AreaSeries_SetSpPr           = window['AscDFH'].historyitem_type_AreaSeries | 8;
	window['AscDFH'].historyitem_AreaSeries_SetTrendline      = window['AscDFH'].historyitem_type_AreaSeries | 9;
	window['AscDFH'].historyitem_AreaSeries_SetTx             = window['AscDFH'].historyitem_type_AreaSeries | 10;
	window['AscDFH'].historyitem_AreaSeries_SetVal            = window['AscDFH'].historyitem_type_AreaSeries | 11;

	window['AscDFH'].historyitem_Cat_SetMultiLvlStrRef = window['AscDFH'].historyitem_type_Cat | 1;
	window['AscDFH'].historyitem_Cat_SetNumLit         = window['AscDFH'].historyitem_type_Cat | 2;
	window['AscDFH'].historyitem_Cat_SetNumRef         = window['AscDFH'].historyitem_type_Cat | 3;
	window['AscDFH'].historyitem_Cat_SetStrLit         = window['AscDFH'].historyitem_type_Cat | 4;
	window['AscDFH'].historyitem_Cat_SetStrRef         = window['AscDFH'].historyitem_type_Cat | 5;

	window['AscDFH'].historyitem_PictureOptions_SetApplyToEnd       = window['AscDFH'].historyitem_type_PictureOptions | 1;
	window['AscDFH'].historyitem_PictureOptions_SetApplyToFront     = window['AscDFH'].historyitem_type_PictureOptions | 2;
	window['AscDFH'].historyitem_PictureOptions_SetApplyToSides     = window['AscDFH'].historyitem_type_PictureOptions | 3;
	window['AscDFH'].historyitem_PictureOptions_SetPictureFormat    = window['AscDFH'].historyitem_type_PictureOptions | 4;
	window['AscDFH'].historyitem_PictureOptions_SetPictureStackUnit = window['AscDFH'].historyitem_type_PictureOptions | 5;

	window['AscDFH'].historyitem_RadarSeries_SetCat    = window['AscDFH'].historyitem_type_RadarSeries | 1;
	window['AscDFH'].historyitem_RadarSeries_SetDLbls  = window['AscDFH'].historyitem_type_RadarSeries | 2;
	window['AscDFH'].historyitem_RadarSeries_SetDPt    = window['AscDFH'].historyitem_type_RadarSeries | 3;
	window['AscDFH'].historyitem_RadarSeries_SetIdx    = window['AscDFH'].historyitem_type_RadarSeries | 4;
	window['AscDFH'].historyitem_RadarSeries_SetMarker = window['AscDFH'].historyitem_type_RadarSeries | 5;
	window['AscDFH'].historyitem_RadarSeries_SetOrder  = window['AscDFH'].historyitem_type_RadarSeries | 6;
	window['AscDFH'].historyitem_RadarSeries_SetSpPr   = window['AscDFH'].historyitem_type_RadarSeries | 7;
	window['AscDFH'].historyitem_RadarSeries_SetTx     = window['AscDFH'].historyitem_type_RadarSeries | 8;
	window['AscDFH'].historyitem_RadarSeries_SetVal    = window['AscDFH'].historyitem_type_RadarSeries | 9;

	window['AscDFH'].historyitem_BarSeries_SetCat              = window['AscDFH'].historyitem_type_BarSeries | 1;
	window['AscDFH'].historyitem_BarSeries_SetDLbls            = window['AscDFH'].historyitem_type_BarSeries | 2;
	window['AscDFH'].historyitem_BarSeries_SetDPt              = window['AscDFH'].historyitem_type_BarSeries | 3;
	window['AscDFH'].historyitem_BarSeries_SetErrBars          = window['AscDFH'].historyitem_type_BarSeries | 4;
	window['AscDFH'].historyitem_BarSeries_SetIdx              = window['AscDFH'].historyitem_type_BarSeries | 5;
	window['AscDFH'].historyitem_BarSeries_SetInvertIfNegative = window['AscDFH'].historyitem_type_BarSeries | 6;
	window['AscDFH'].historyitem_BarSeries_SetOrder            = window['AscDFH'].historyitem_type_BarSeries | 7;
	window['AscDFH'].historyitem_BarSeries_SetPictureOptions   = window['AscDFH'].historyitem_type_BarSeries | 8;
	window['AscDFH'].historyitem_BarSeries_SetShape            = window['AscDFH'].historyitem_type_BarSeries | 9;
	window['AscDFH'].historyitem_BarSeries_SetSpPr             = window['AscDFH'].historyitem_type_BarSeries | 10;
	window['AscDFH'].historyitem_BarSeries_SetTrendline        = window['AscDFH'].historyitem_type_BarSeries | 11;
	window['AscDFH'].historyitem_BarSeries_SetTx               = window['AscDFH'].historyitem_type_BarSeries | 12;
	window['AscDFH'].historyitem_BarSeries_SetVal              = window['AscDFH'].historyitem_type_BarSeries | 13;

	window['AscDFH'].historyitem_LineSeries_SetCat       = window['AscDFH'].historyitem_type_LineSeries | 1;
	window['AscDFH'].historyitem_LineSeries_SetDLbls     = window['AscDFH'].historyitem_type_LineSeries | 2;
	window['AscDFH'].historyitem_LineSeries_SetDPt       = window['AscDFH'].historyitem_type_LineSeries | 3;
	window['AscDFH'].historyitem_LineSeries_SetErrBars   = window['AscDFH'].historyitem_type_LineSeries | 4;
	window['AscDFH'].historyitem_LineSeries_SetIdx       = window['AscDFH'].historyitem_type_LineSeries | 5;
	window['AscDFH'].historyitem_LineSeries_SetMarker    = window['AscDFH'].historyitem_type_LineSeries | 6;
	window['AscDFH'].historyitem_LineSeries_SetOrder     = window['AscDFH'].historyitem_type_LineSeries | 7;
	window['AscDFH'].historyitem_LineSeries_SetSmooth    = window['AscDFH'].historyitem_type_LineSeries | 8;
	window['AscDFH'].historyitem_LineSeries_SetSpPr      = window['AscDFH'].historyitem_type_LineSeries | 9;
	window['AscDFH'].historyitem_LineSeries_SetTrendline = window['AscDFH'].historyitem_type_LineSeries | 10;
	window['AscDFH'].historyitem_LineSeries_SetTx        = window['AscDFH'].historyitem_type_LineSeries | 11;
	window['AscDFH'].historyitem_LineSeries_SetVal       = window['AscDFH'].historyitem_type_LineSeries | 12;

	window['AscDFH'].historyitem_PieSeries_SetCat       = window['AscDFH'].historyitem_type_PieSeries | 1;
	window['AscDFH'].historyitem_PieSeries_SetDLbls     = window['AscDFH'].historyitem_type_PieSeries | 2;
	window['AscDFH'].historyitem_PieSeries_SetDPt       = window['AscDFH'].historyitem_type_PieSeries | 3;
	window['AscDFH'].historyitem_PieSeries_SetExplosion = window['AscDFH'].historyitem_type_PieSeries | 4;
	window['AscDFH'].historyitem_PieSeries_SetIdx       = window['AscDFH'].historyitem_type_PieSeries | 5;
	window['AscDFH'].historyitem_PieSeries_SetOrder     = window['AscDFH'].historyitem_type_PieSeries | 6;
	window['AscDFH'].historyitem_PieSeries_SetSpPr      = window['AscDFH'].historyitem_type_PieSeries | 7;
	window['AscDFH'].historyitem_PieSeries_SetTx        = window['AscDFH'].historyitem_type_PieSeries | 8;
	window['AscDFH'].historyitem_PieSeries_SetVal       = window['AscDFH'].historyitem_type_PieSeries | 9;

	window['AscDFH'].historyitem_SurfaceSeries_SetCat   = window['AscDFH'].historyitem_type_SurfaceSeries | 1;
	window['AscDFH'].historyitem_SurfaceSeries_SetIdx   = window['AscDFH'].historyitem_type_SurfaceSeries | 2;
	window['AscDFH'].historyitem_SurfaceSeries_SetOrder = window['AscDFH'].historyitem_type_SurfaceSeries | 3;
	window['AscDFH'].historyitem_SurfaceSeries_SetSpPr  = window['AscDFH'].historyitem_type_SurfaceSeries | 4;
	window['AscDFH'].historyitem_SurfaceSeries_SetTx    = window['AscDFH'].historyitem_type_SurfaceSeries | 5;
	window['AscDFH'].historyitem_SurfaceSeries_SetVal   = window['AscDFH'].historyitem_type_SurfaceSeries | 6;

	window['AscDFH'].historyitem_BubbleSeries_SetBubble3D         = window['AscDFH'].historyitem_type_BubbleSeries | 1;
	window['AscDFH'].historyitem_BubbleSeries_SetBubbleSize       = window['AscDFH'].historyitem_type_BubbleSeries | 2;
	window['AscDFH'].historyitem_BubbleSeries_SetDLbls            = window['AscDFH'].historyitem_type_BubbleSeries | 3;
	window['AscDFH'].historyitem_BubbleSeries_SetDPt              = window['AscDFH'].historyitem_type_BubbleSeries | 4;
	window['AscDFH'].historyitem_BubbleSeries_SetErrBars          = window['AscDFH'].historyitem_type_BubbleSeries | 5;
	window['AscDFH'].historyitem_BubbleSeries_SetIdx              = window['AscDFH'].historyitem_type_BubbleSeries | 6;
	window['AscDFH'].historyitem_BubbleSeries_SetInvertIfNegative = window['AscDFH'].historyitem_type_BubbleSeries | 7;
	window['AscDFH'].historyitem_BubbleSeries_SetOrder            = window['AscDFH'].historyitem_type_BubbleSeries | 8;
	window['AscDFH'].historyitem_BubbleSeries_SetSpPr             = window['AscDFH'].historyitem_type_BubbleSeries | 9;
	window['AscDFH'].historyitem_BubbleSeries_SetTrendline        = window['AscDFH'].historyitem_type_BubbleSeries | 10;
	window['AscDFH'].historyitem_BubbleSeries_SetTx               = window['AscDFH'].historyitem_type_BubbleSeries | 11;
	window['AscDFH'].historyitem_BubbleSeries_SetXVal             = window['AscDFH'].historyitem_type_BubbleSeries | 12;
	window['AscDFH'].historyitem_BubbleSeries_SetYVal             = window['AscDFH'].historyitem_type_BubbleSeries | 13;

	window['AscDFH'].historyitem_ExternalData_SetAutoUpdate = window['AscDFH'].historyitem_type_ExternalData | 1;
	window['AscDFH'].historyitem_ExternalData_SetId         = window['AscDFH'].historyitem_type_ExternalData | 2;

	window['AscDFH'].historyitem_PivotSource_SetFmtId = window['AscDFH'].historyitem_type_PivotSource | 1;
	window['AscDFH'].historyitem_PivotSource_SetName  = window['AscDFH'].historyitem_type_PivotSource | 2;

	window['AscDFH'].historyitem_Protection_SetChartObject   = window['AscDFH'].historyitem_type_Protection | 1;
	window['AscDFH'].historyitem_Protection_SetData          = window['AscDFH'].historyitem_type_Protection | 2;
	window['AscDFH'].historyitem_Protection_SetFormatting    = window['AscDFH'].historyitem_type_Protection | 3;
	window['AscDFH'].historyitem_Protection_SetSelection     = window['AscDFH'].historyitem_type_Protection | 4;
	window['AscDFH'].historyitem_Protection_SetUserInterface = window['AscDFH'].historyitem_type_Protection | 5;

	window['AscDFH'].historyitem_ChartWall_SetPictureOptions = window['AscDFH'].historyitem_type_ChartWall | 1;
	window['AscDFH'].historyitem_ChartWall_SetSpPr           = window['AscDFH'].historyitem_type_ChartWall | 2;
	window['AscDFH'].historyitem_ChartWall_SetThickness      = window['AscDFH'].historyitem_type_ChartWall | 3;

	window['AscDFH'].historyitem_View3d_SetDepthPercent = window['AscDFH'].historyitem_type_View3d | 1;
	window['AscDFH'].historyitem_View3d_SetHPercent     = window['AscDFH'].historyitem_type_View3d | 2;
	window['AscDFH'].historyitem_View3d_SetPerspective  = window['AscDFH'].historyitem_type_View3d | 3;
	window['AscDFH'].historyitem_View3d_SetRAngAx       = window['AscDFH'].historyitem_type_View3d | 4;
	window['AscDFH'].historyitem_View3d_SetRotX         = window['AscDFH'].historyitem_type_View3d | 5;
	window['AscDFH'].historyitem_View3d_SetRotY         = window['AscDFH'].historyitem_type_View3d | 6;

	window['AscDFH'].historyitem_ChartText_SetRich   = window['AscDFH'].historyitem_type_ChartText | 1;
	window['AscDFH'].historyitem_ChartText_SetStrRef = window['AscDFH'].historyitem_type_ChartText | 2;

	window['AscDFH'].historyitem_ShapeStyle_SetLnRef     = window['AscDFH'].historyitem_type_ShapeStyle | 1;
	window['AscDFH'].historyitem_ShapeStyle_SetFillRef   = window['AscDFH'].historyitem_type_ShapeStyle | 2;
	window['AscDFH'].historyitem_ShapeStyle_SetFontRef   = window['AscDFH'].historyitem_type_ShapeStyle | 3;
	window['AscDFH'].historyitem_ShapeStyle_SetEffectRef = window['AscDFH'].historyitem_type_ShapeStyle | 4;

	window['AscDFH'].historyitem_Xfrm_SetOffX   = window['AscDFH'].historyitem_type_Xfrm | 1;
	window['AscDFH'].historyitem_Xfrm_SetOffY   = window['AscDFH'].historyitem_type_Xfrm | 2;
	window['AscDFH'].historyitem_Xfrm_SetExtX   = window['AscDFH'].historyitem_type_Xfrm | 3;
	window['AscDFH'].historyitem_Xfrm_SetExtY   = window['AscDFH'].historyitem_type_Xfrm | 4;
	window['AscDFH'].historyitem_Xfrm_SetChOffX = window['AscDFH'].historyitem_type_Xfrm | 5;
	window['AscDFH'].historyitem_Xfrm_SetChOffY = window['AscDFH'].historyitem_type_Xfrm | 6;
	window['AscDFH'].historyitem_Xfrm_SetChExtX = window['AscDFH'].historyitem_type_Xfrm | 7;
	window['AscDFH'].historyitem_Xfrm_SetChExtY = window['AscDFH'].historyitem_type_Xfrm | 8;
	window['AscDFH'].historyitem_Xfrm_SetFlipH  = window['AscDFH'].historyitem_type_Xfrm | 9;
	window['AscDFH'].historyitem_Xfrm_SetFlipV  = window['AscDFH'].historyitem_type_Xfrm | 10;
	window['AscDFH'].historyitem_Xfrm_SetRot    = window['AscDFH'].historyitem_type_Xfrm | 11;
	window['AscDFH'].historyitem_Xfrm_SetParent = window['AscDFH'].historyitem_type_Xfrm | 12;

	window['AscDFH'].historyitem_SpPr_SetBwMode   = window['AscDFH'].historyitem_type_SpPr | 1;
	window['AscDFH'].historyitem_SpPr_SetXfrm     = window['AscDFH'].historyitem_type_SpPr | 2;
	window['AscDFH'].historyitem_SpPr_SetGeometry = window['AscDFH'].historyitem_type_SpPr | 3;
	window['AscDFH'].historyitem_SpPr_SetFill     = window['AscDFH'].historyitem_type_SpPr | 4;
	window['AscDFH'].historyitem_SpPr_SetLn       = window['AscDFH'].historyitem_type_SpPr | 5;
	window['AscDFH'].historyitem_SpPr_SetParent   = window['AscDFH'].historyitem_type_SpPr | 6;

	window['AscDFH'].historyitem_ClrScheme_AddClr  = window['AscDFH'].historyitem_type_ClrScheme | 1;
	window['AscDFH'].historyitem_ClrScheme_SetName = window['AscDFH'].historyitem_type_ClrScheme | 2;

	window['AscDFH'].historyitem_ClrMap_SetClr = window['AscDFH'].historyitem_type_ClrMap | 1;

	window['AscDFH'].historyitem_ExtraClrScheme_SetClrScheme = window['AscDFH'].historyitem_type_ExtraClrScheme | 1;
	window['AscDFH'].historyitem_ExtraClrScheme_SetClrMap    = window['AscDFH'].historyitem_type_ExtraClrScheme | 2;

	window['AscDFH'].historyitem_FontCollection_SetFontScheme = window['AscDFH'].historyitem_type_FontCollection | 1;
	window['AscDFH'].historyitem_FontCollection_SetLatin      = window['AscDFH'].historyitem_type_FontCollection | 2;
	window['AscDFH'].historyitem_FontCollection_SetEA         = window['AscDFH'].historyitem_type_FontCollection | 3;
	window['AscDFH'].historyitem_FontCollection_SetCS         = window['AscDFH'].historyitem_type_FontCollection | 4;

	window['AscDFH'].historyitem_FontScheme_SetName      = window['AscDFH'].historyitem_type_FontScheme | 1;
	window['AscDFH'].historyitem_FontScheme_SetMajorFont = window['AscDFH'].historyitem_type_FontScheme | 2;
	window['AscDFH'].historyitem_FontScheme_SetMinorFont = window['AscDFH'].historyitem_type_FontScheme | 3;

	window['AscDFH'].historyitem_FormatScheme_SetName             = window['AscDFH'].historyitem_type_FormatScheme | 1;
	window['AscDFH'].historyitem_FormatScheme_AddFillToStyleLst   = window['AscDFH'].historyitem_type_FormatScheme | 2;
	window['AscDFH'].historyitem_FormatScheme_AddLnToStyleLst     = window['AscDFH'].historyitem_type_FormatScheme | 3;
	window['AscDFH'].historyitem_FormatScheme_AddEffectToStyleLst = window['AscDFH'].historyitem_type_FormatScheme | 4;
	window['AscDFH'].historyitem_FormatScheme_AddBgFillToStyleLst = window['AscDFH'].historyitem_type_FormatScheme | 5;

	window['AscDFH'].historyitem_ThemeElements_SetClrScheme  = window['AscDFH'].historyitem_type_ThemeElements | 1;
	window['AscDFH'].historyitem_ThemeElements_SetFontScheme = window['AscDFH'].historyitem_type_ThemeElements | 2;
	window['AscDFH'].historyitem_ThemeElements_SetFmtScheme  = window['AscDFH'].historyitem_type_ThemeElements | 3;

	window['AscDFH'].historyitem_HF_SetDt     = window['AscDFH'].historyitem_type_HF | 1;
	window['AscDFH'].historyitem_HF_SetFtr    = window['AscDFH'].historyitem_type_HF | 2;
	window['AscDFH'].historyitem_HF_SetHdr    = window['AscDFH'].historyitem_type_HF | 3;
	window['AscDFH'].historyitem_HF_SetSldNum = window['AscDFH'].historyitem_type_HF | 4;

	window['AscDFH'].historyitem_BgPr_SetFill         = window['AscDFH'].historyitem_type_BgPr | 1;
	window['AscDFH'].historyitem_BgPr_SetShadeToTitle = window['AscDFH'].historyitem_type_BgPr | 2;

	window['AscDFH'].historyitem_BgSetBwMode = window['AscDFH'].historyitem_type_Bg | 1;
	window['AscDFH'].historyitem_BgSetBgPr   = window['AscDFH'].historyitem_type_Bg | 2;
	window['AscDFH'].historyitem_BgSetBgRef  = window['AscDFH'].historyitem_type_Bg | 3;

	window['AscDFH'].historyitem_PrintSettingsSetHeaderFooter = window['AscDFH'].historyitem_type_PrintSettings | 1;
	window['AscDFH'].historyitem_PrintSettingsSetPageMargins  = window['AscDFH'].historyitem_type_PrintSettings | 2;
	window['AscDFH'].historyitem_PrintSettingsSetPageSetup    = window['AscDFH'].historyitem_type_PrintSettings | 3;

	window['AscDFH'].historyitem_HeaderFooterChartSetAlignWithMargins = window['AscDFH'].historyitem_type_HeaderFooterChart | 1;
	window['AscDFH'].historyitem_HeaderFooterChartSetDifferentFirst   = window['AscDFH'].historyitem_type_HeaderFooterChart | 2;
	window['AscDFH'].historyitem_HeaderFooterChartSetDifferentOddEven = window['AscDFH'].historyitem_type_HeaderFooterChart | 3;
	window['AscDFH'].historyitem_HeaderFooterChartSetEvenFooter       = window['AscDFH'].historyitem_type_HeaderFooterChart | 4;
	window['AscDFH'].historyitem_HeaderFooterChartSetEvenHeader       = window['AscDFH'].historyitem_type_HeaderFooterChart | 5;
	window['AscDFH'].historyitem_HeaderFooterChartSetFirstFooter      = window['AscDFH'].historyitem_type_HeaderFooterChart | 6;
	window['AscDFH'].historyitem_HeaderFooterChartSetFirstHeader      = window['AscDFH'].historyitem_type_HeaderFooterChart | 7;
	window['AscDFH'].historyitem_HeaderFooterChartSetOddFooter        = window['AscDFH'].historyitem_type_HeaderFooterChart | 8;
	window['AscDFH'].historyitem_HeaderFooterChartSetOddHeader        = window['AscDFH'].historyitem_type_HeaderFooterChart | 9;

	window['AscDFH'].historyitem_PageMarginsSetB      = window['AscDFH'].historyitem_type_PageMarginsChart | 1;
	window['AscDFH'].historyitem_PageMarginsSetFooter = window['AscDFH'].historyitem_type_PageMarginsChart | 2;
	window['AscDFH'].historyitem_PageMarginsSetHeader = window['AscDFH'].historyitem_type_PageMarginsChart | 3;
	window['AscDFH'].historyitem_PageMarginsSetL      = window['AscDFH'].historyitem_type_PageMarginsChart | 4;
	window['AscDFH'].historyitem_PageMarginsSetR      = window['AscDFH'].historyitem_type_PageMarginsChart | 5;
	window['AscDFH'].historyitem_PageMarginsSetT      = window['AscDFH'].historyitem_type_PageMarginsChart | 6;

	window['AscDFH'].historyitem_PageSetupSetBlackAndWhite    = window['AscDFH'].historyitem_type_PageSetup | 1;
	window['AscDFH'].historyitem_PageSetupSetCopies           = window['AscDFH'].historyitem_type_PageSetup | 2;
	window['AscDFH'].historyitem_PageSetupSetDraft            = window['AscDFH'].historyitem_type_PageSetup | 3;
	window['AscDFH'].historyitem_PageSetupSetFirstPageNumber  = window['AscDFH'].historyitem_type_PageSetup | 4;
	window['AscDFH'].historyitem_PageSetupSetHorizontalDpi    = window['AscDFH'].historyitem_type_PageSetup | 5;
	window['AscDFH'].historyitem_PageSetupSetOrientation      = window['AscDFH'].historyitem_type_PageSetup | 6;
	window['AscDFH'].historyitem_PageSetupSetPaperHeight      = window['AscDFH'].historyitem_type_PageSetup | 7;
	window['AscDFH'].historyitem_PageSetupSetPaperSize        = window['AscDFH'].historyitem_type_PageSetup | 8;
	window['AscDFH'].historyitem_PageSetupSetPaperWidth       = window['AscDFH'].historyitem_type_PageSetup | 9;
	window['AscDFH'].historyitem_PageSetupSetUseFirstPageNumb = window['AscDFH'].historyitem_type_PageSetup | 10;
	window['AscDFH'].historyitem_PageSetupSetVerticalDpi      = window['AscDFH'].historyitem_type_PageSetup | 11;

	window['AscDFH'].historyitem_ShapeSetBDeleted       = window['AscDFH'].historyitem_type_Shape | 1;
	window['AscDFH'].historyitem_ShapeSetNvSpPr         = window['AscDFH'].historyitem_type_Shape | 2;
	window['AscDFH'].historyitem_ShapeSetSpPr           = window['AscDFH'].historyitem_type_Shape | 3;
	window['AscDFH'].historyitem_ShapeSetStyle          = window['AscDFH'].historyitem_type_Shape | 4;
	window['AscDFH'].historyitem_ShapeSetTxBody         = window['AscDFH'].historyitem_type_Shape | 5;
	window['AscDFH'].historyitem_ShapeSetTextBoxContent = window['AscDFH'].historyitem_type_Shape | 6;
	window['AscDFH'].historyitem_ShapeSetParent         = window['AscDFH'].historyitem_type_Shape | 7;
	window['AscDFH'].historyitem_ShapeSetGroup          = window['AscDFH'].historyitem_type_Shape | 8;
	window['AscDFH'].historyitem_ShapeSetBodyPr         = window['AscDFH'].historyitem_type_Shape | 9;
	window['AscDFH'].historyitem_ShapeSetWordShape      = window['AscDFH'].historyitem_type_Shape | 10;
	window['AscDFH'].historyitem_ShapeSetSignature      = window['AscDFH'].historyitem_type_Shape | 11;

	window['AscDFH'].historyitem_DispUnitsSetBuiltInUnit  = window['AscDFH'].historyitem_type_DispUnits | 1;
	window['AscDFH'].historyitem_DispUnitsSetCustUnit     = window['AscDFH'].historyitem_type_DispUnits | 2;
	window['AscDFH'].historyitem_DispUnitsSetDispUnitsLbl = window['AscDFH'].historyitem_type_DispUnits | 3;
	window['AscDFH'].historyitem_DispUnitsSetParent       = window['AscDFH'].historyitem_type_DispUnits | 4;

	window['AscDFH'].historyitem_GroupShapeSetNvGrpSpPr     = window['AscDFH'].historyitem_type_GroupShape | 1;
	window['AscDFH'].historyitem_GroupShapeSetSpPr          = window['AscDFH'].historyitem_type_GroupShape | 2;
	window['AscDFH'].historyitem_GroupShapeAddToSpTree      = window['AscDFH'].historyitem_type_GroupShape | 3;
	window['AscDFH'].historyitem_GroupShapeSetParent        = window['AscDFH'].historyitem_type_GroupShape | 4;
	window['AscDFH'].historyitem_GroupShapeSetGroup         = window['AscDFH'].historyitem_type_GroupShape | 5;
	window['AscDFH'].historyitem_GroupShapeRemoveFromSpTree = window['AscDFH'].historyitem_type_GroupShape | 6;

	window['AscDFH'].historyitem_ImageShapeSetNvPicPr       = window['AscDFH'].historyitem_type_ImageShape | 1;
	window['AscDFH'].historyitem_ImageShapeSetSpPr          = window['AscDFH'].historyitem_type_ImageShape | 2;
	window['AscDFH'].historyitem_ImageShapeSetBlipFill      = window['AscDFH'].historyitem_type_ImageShape | 3;
	window['AscDFH'].historyitem_ImageShapeSetParent        = window['AscDFH'].historyitem_type_ImageShape | 4;
	window['AscDFH'].historyitem_ImageShapeSetGroup         = window['AscDFH'].historyitem_type_ImageShape | 5;
	window['AscDFH'].historyitem_ImageShapeSetStyle         = window['AscDFH'].historyitem_type_ImageShape | 6;
	window['AscDFH'].historyitem_ImageShapeSetData          = window['AscDFH'].historyitem_type_ImageShape | 7;
	window['AscDFH'].historyitem_ImageShapeSetApplicationId = window['AscDFH'].historyitem_type_ImageShape | 8;
	window['AscDFH'].historyitem_ImageShapeSetPixSizes      = window['AscDFH'].historyitem_type_ImageShape | 9;
	window['AscDFH'].historyitem_ImageShapeSetObjectFile	= window['AscDFH'].historyitem_type_ImageShape | 10;

	window['AscDFH'].historyitem_GeometrySetParent      = window['AscDFH'].historyitem_type_Geometry | 1;
	window['AscDFH'].historyitem_GeometryAddAdj         = window['AscDFH'].historyitem_type_Geometry | 2;
	window['AscDFH'].historyitem_GeometryAddGuide       = window['AscDFH'].historyitem_type_Geometry | 3;
	window['AscDFH'].historyitem_GeometryAddCnx         = window['AscDFH'].historyitem_type_Geometry | 4;
	window['AscDFH'].historyitem_GeometryAddHandleXY    = window['AscDFH'].historyitem_type_Geometry | 5;
	window['AscDFH'].historyitem_GeometryAddHandlePolar = window['AscDFH'].historyitem_type_Geometry | 6;
	window['AscDFH'].historyitem_GeometryAddPath        = window['AscDFH'].historyitem_type_Geometry | 7;
	window['AscDFH'].historyitem_GeometryAddRect        = window['AscDFH'].historyitem_type_Geometry | 8;
	window['AscDFH'].historyitem_GeometrySetPreset      = window['AscDFH'].historyitem_type_Geometry | 9;

	window['AscDFH'].historyitem_PathSetStroke      = window['AscDFH'].historyitem_type_Path | 1;
	window['AscDFH'].historyitem_PathSetExtrusionOk = window['AscDFH'].historyitem_type_Path | 2;
	window['AscDFH'].historyitem_PathSetFill        = window['AscDFH'].historyitem_type_Path | 3;
	window['AscDFH'].historyitem_PathSetPathH       = window['AscDFH'].historyitem_type_Path | 4;
	window['AscDFH'].historyitem_PathSetPathW       = window['AscDFH'].historyitem_type_Path | 5;
	window['AscDFH'].historyitem_PathAddPathCommand = window['AscDFH'].historyitem_type_Path | 6;

	window['AscDFH'].historyitem_TextBodySetBodyPr   = window['AscDFH'].historyitem_type_TextBody | 1;
	window['AscDFH'].historyitem_TextBodySetLstStyle = window['AscDFH'].historyitem_type_TextBody | 2;
	window['AscDFH'].historyitem_TextBodySetContent  = window['AscDFH'].historyitem_type_TextBody | 3;
	window['AscDFH'].historyitem_TextBodySetParent   = window['AscDFH'].historyitem_type_TextBody | 4;

	window['AscDFH'].historyitem_CatAxSetAuto           = window['AscDFH'].historyitem_type_CatAx | 1;
	window['AscDFH'].historyitem_CatAxSetAxId           = window['AscDFH'].historyitem_type_CatAx | 2;
	window['AscDFH'].historyitem_CatAxSetAxPos          = window['AscDFH'].historyitem_type_CatAx | 3;
	window['AscDFH'].historyitem_CatAxSetCrossAx        = window['AscDFH'].historyitem_type_CatAx | 4;
	window['AscDFH'].historyitem_CatAxSetCrosses        = window['AscDFH'].historyitem_type_CatAx | 5;
	window['AscDFH'].historyitem_CatAxSetCrossesAt      = window['AscDFH'].historyitem_type_CatAx | 6;
	window['AscDFH'].historyitem_CatAxSetDelete         = window['AscDFH'].historyitem_type_CatAx | 7;
	window['AscDFH'].historyitem_CatAxSetLblAlgn        = window['AscDFH'].historyitem_type_CatAx | 8;
	window['AscDFH'].historyitem_CatAxSetLblOffset      = window['AscDFH'].historyitem_type_CatAx | 9;
	window['AscDFH'].historyitem_CatAxSetMajorGridlines = window['AscDFH'].historyitem_type_CatAx | 10;
	window['AscDFH'].historyitem_CatAxSetMajorTickMark  = window['AscDFH'].historyitem_type_CatAx | 11;
	window['AscDFH'].historyitem_CatAxSetMinorGridlines = window['AscDFH'].historyitem_type_CatAx | 12;
	window['AscDFH'].historyitem_CatAxSetMinorTickMark  = window['AscDFH'].historyitem_type_CatAx | 13;
	window['AscDFH'].historyitem_CatAxSetNoMultiLvlLbl  = window['AscDFH'].historyitem_type_CatAx | 14;
	window['AscDFH'].historyitem_CatAxSetNumFmt         = window['AscDFH'].historyitem_type_CatAx | 15;
	window['AscDFH'].historyitem_CatAxSetScaling        = window['AscDFH'].historyitem_type_CatAx | 16;
	window['AscDFH'].historyitem_CatAxSetSpPr           = window['AscDFH'].historyitem_type_CatAx | 17;
	window['AscDFH'].historyitem_CatAxSetTickLblPos     = window['AscDFH'].historyitem_type_CatAx | 18;
	window['AscDFH'].historyitem_CatAxSetTickLblSkip    = window['AscDFH'].historyitem_type_CatAx | 19;
	window['AscDFH'].historyitem_CatAxSetTickMarkSkip   = window['AscDFH'].historyitem_type_CatAx | 20;
	window['AscDFH'].historyitem_CatAxSetTitle          = window['AscDFH'].historyitem_type_CatAx | 21;
	window['AscDFH'].historyitem_CatAxSetTxPr           = window['AscDFH'].historyitem_type_CatAx | 22;

	window['AscDFH'].historyitem_ValAxSetAxId           = window['AscDFH'].historyitem_type_ValAx | 1;
	window['AscDFH'].historyitem_ValAxSetAxPos          = window['AscDFH'].historyitem_type_ValAx | 2;
	window['AscDFH'].historyitem_ValAxSetCrossAx        = window['AscDFH'].historyitem_type_ValAx | 3;
	window['AscDFH'].historyitem_ValAxSetCrossBetween   = window['AscDFH'].historyitem_type_ValAx | 4;
	window['AscDFH'].historyitem_ValAxSetCrosses        = window['AscDFH'].historyitem_type_ValAx | 5;
	window['AscDFH'].historyitem_ValAxSetCrossesAt      = window['AscDFH'].historyitem_type_ValAx | 6;
	window['AscDFH'].historyitem_ValAxSetDelete         = window['AscDFH'].historyitem_type_ValAx | 7;
	window['AscDFH'].historyitem_ValAxSetDispUnits      = window['AscDFH'].historyitem_type_ValAx | 8;
	window['AscDFH'].historyitem_ValAxSetMajorGridlines = window['AscDFH'].historyitem_type_ValAx | 9;
	window['AscDFH'].historyitem_ValAxSetMajorTickMark  = window['AscDFH'].historyitem_type_ValAx | 10;
	window['AscDFH'].historyitem_ValAxSetMajorUnit      = window['AscDFH'].historyitem_type_ValAx | 11;
	window['AscDFH'].historyitem_ValAxSetMinorGridlines = window['AscDFH'].historyitem_type_ValAx | 12;
	window['AscDFH'].historyitem_ValAxSetMinorTickMark  = window['AscDFH'].historyitem_type_ValAx | 13;
	window['AscDFH'].historyitem_ValAxSetMinorUnit      = window['AscDFH'].historyitem_type_ValAx | 14;
	window['AscDFH'].historyitem_ValAxSetNumFmt         = window['AscDFH'].historyitem_type_ValAx | 15;
	window['AscDFH'].historyitem_ValAxSetScaling        = window['AscDFH'].historyitem_type_ValAx | 16;
	window['AscDFH'].historyitem_ValAxSetSpPr           = window['AscDFH'].historyitem_type_ValAx | 17;
	window['AscDFH'].historyitem_ValAxSetTickLblPos     = window['AscDFH'].historyitem_type_ValAx | 18;
	window['AscDFH'].historyitem_ValAxSetTitle          = window['AscDFH'].historyitem_type_ValAx | 19;
	window['AscDFH'].historyitem_ValAxSetTxPr           = window['AscDFH'].historyitem_type_ValAx | 20;

	window['AscDFH'].historyitem_WrapPolygonSetEdited    = window['AscDFH'].historyitem_type_WrapPolygon | 1;
	window['AscDFH'].historyitem_WrapPolygonSetRelPoints = window['AscDFH'].historyitem_type_WrapPolygon | 2;
	window['AscDFH'].historyitem_WrapPolygonSetWrapSide  = window['AscDFH'].historyitem_type_WrapPolygon | 3;

	window['AscDFH'].historyitem_DateAxAuto           = window['AscDFH'].historyitem_type_DateAx | 1;
	window['AscDFH'].historyitem_DateAxAxId           = window['AscDFH'].historyitem_type_DateAx | 2;
	window['AscDFH'].historyitem_DateAxAxPos          = window['AscDFH'].historyitem_type_DateAx | 3;
	window['AscDFH'].historyitem_DateAxBaseTimeUnit   = window['AscDFH'].historyitem_type_DateAx | 4;
	window['AscDFH'].historyitem_DateAxCrossAx        = window['AscDFH'].historyitem_type_DateAx | 5;
	window['AscDFH'].historyitem_DateAxCrosses        = window['AscDFH'].historyitem_type_DateAx | 6;
	window['AscDFH'].historyitem_DateAxCrossesAt      = window['AscDFH'].historyitem_type_DateAx | 7;
	window['AscDFH'].historyitem_DateAxDelete         = window['AscDFH'].historyitem_type_DateAx | 8;
	window['AscDFH'].historyitem_DateAxLblOffset      = window['AscDFH'].historyitem_type_DateAx | 9;
	window['AscDFH'].historyitem_DateAxMajorGridlines = window['AscDFH'].historyitem_type_DateAx | 10;
	window['AscDFH'].historyitem_DateAxMajorTickMark  = window['AscDFH'].historyitem_type_DateAx | 11;
	window['AscDFH'].historyitem_DateAxMajorTimeUnit  = window['AscDFH'].historyitem_type_DateAx | 12;
	window['AscDFH'].historyitem_DateAxMajorUnit      = window['AscDFH'].historyitem_type_DateAx | 13;
	window['AscDFH'].historyitem_DateAxMinorGridlines = window['AscDFH'].historyitem_type_DateAx | 14;
	window['AscDFH'].historyitem_DateAxMinorTickMark  = window['AscDFH'].historyitem_type_DateAx | 15;
	window['AscDFH'].historyitem_DateAxMinorTimeUnit  = window['AscDFH'].historyitem_type_DateAx | 16;
	window['AscDFH'].historyitem_DateAxMinorUnit      = window['AscDFH'].historyitem_type_DateAx | 17;
	window['AscDFH'].historyitem_DateAxNumFmt         = window['AscDFH'].historyitem_type_DateAx | 18;
	window['AscDFH'].historyitem_DateAxScaling        = window['AscDFH'].historyitem_type_DateAx | 19;
	window['AscDFH'].historyitem_DateAxSpPr           = window['AscDFH'].historyitem_type_DateAx | 20;
	window['AscDFH'].historyitem_DateAxTickLblPos     = window['AscDFH'].historyitem_type_DateAx | 21;
	window['AscDFH'].historyitem_DateAxTitle          = window['AscDFH'].historyitem_type_DateAx | 22;
	window['AscDFH'].historyitem_DateAxTxPr           = window['AscDFH'].historyitem_type_DateAx | 23;

	window['AscDFH'].historyitem_SerAxSetAxId           = window['AscDFH'].historyitem_type_SerAx | 1;
	window['AscDFH'].historyitem_SerAxSetAxPos          = window['AscDFH'].historyitem_type_SerAx | 2;
	window['AscDFH'].historyitem_SerAxSetCrossAx        = window['AscDFH'].historyitem_type_SerAx | 3;
	window['AscDFH'].historyitem_SerAxSetCrosses        = window['AscDFH'].historyitem_type_SerAx | 4;
	window['AscDFH'].historyitem_SerAxSetCrossesAt      = window['AscDFH'].historyitem_type_SerAx | 5;
	window['AscDFH'].historyitem_SerAxSetDelete         = window['AscDFH'].historyitem_type_SerAx | 6;
	window['AscDFH'].historyitem_SerAxSetMajorGridlines = window['AscDFH'].historyitem_type_SerAx | 7;
	window['AscDFH'].historyitem_SerAxSetMajorTickMark  = window['AscDFH'].historyitem_type_SerAx | 8;
	window['AscDFH'].historyitem_SerAxSetMinorGridlines = window['AscDFH'].historyitem_type_SerAx | 9;
	window['AscDFH'].historyitem_SerAxSetMinorTickMark  = window['AscDFH'].historyitem_type_SerAx | 10;
	window['AscDFH'].historyitem_SerAxSetNumFmt         = window['AscDFH'].historyitem_type_SerAx | 11;
	window['AscDFH'].historyitem_SerAxSetScaling        = window['AscDFH'].historyitem_type_SerAx | 12;
	window['AscDFH'].historyitem_SerAxSetSpPr           = window['AscDFH'].historyitem_type_SerAx | 13;
	window['AscDFH'].historyitem_SerAxSetTickLblPos     = window['AscDFH'].historyitem_type_SerAx | 14;
	window['AscDFH'].historyitem_SerAxSetTickLblSkip    = window['AscDFH'].historyitem_type_SerAx | 15;
	window['AscDFH'].historyitem_SerAxSetTickMarkSkip   = window['AscDFH'].historyitem_type_SerAx | 16;
	window['AscDFH'].historyitem_SerAxSetTitle          = window['AscDFH'].historyitem_type_SerAx | 17;
	window['AscDFH'].historyitem_SerAxSetTxPr           = window['AscDFH'].historyitem_type_SerAx | 18;

	window['AscDFH'].historyitem_Title_SetLayout  = window['AscDFH'].historyitem_type_Title | 1;
	window['AscDFH'].historyitem_Title_SetOverlay = window['AscDFH'].historyitem_type_Title | 2;
	window['AscDFH'].historyitem_Title_SetSpPr    = window['AscDFH'].historyitem_type_Title | 3;
	window['AscDFH'].historyitem_Title_SetTx      = window['AscDFH'].historyitem_type_Title | 4;
	window['AscDFH'].historyitem_Title_SetTxPr    = window['AscDFH'].historyitem_type_Title | 5;

	window['AscDFH'].historyitem_SlideSetComments       = window['AscDFH'].historyitem_type_Slide | 1;
	window['AscDFH'].historyitem_SlideSetShow           = window['AscDFH'].historyitem_type_Slide | 2;
	window['AscDFH'].historyitem_SlideSetShowPhAnim     = window['AscDFH'].historyitem_type_Slide | 3;
	window['AscDFH'].historyitem_SlideSetShowMasterSp   = window['AscDFH'].historyitem_type_Slide | 4;
	window['AscDFH'].historyitem_SlideSetLayout         = window['AscDFH'].historyitem_type_Slide | 5;
	window['AscDFH'].historyitem_SlideSetNum            = window['AscDFH'].historyitem_type_Slide | 6;
	window['AscDFH'].historyitem_SlideSetTiming         = window['AscDFH'].historyitem_type_Slide | 7;
	window['AscDFH'].historyitem_SlideSetSize           = window['AscDFH'].historyitem_type_Slide | 8;
	window['AscDFH'].historyitem_SlideSetBg             = window['AscDFH'].historyitem_type_Slide | 9;
	window['AscDFH'].historyitem_SlideSetLocks          = window['AscDFH'].historyitem_type_Slide | 10;
	window['AscDFH'].historyitem_SlideRemoveFromSpTree  = window['AscDFH'].historyitem_type_Slide | 11;
	window['AscDFH'].historyitem_SlideAddToSpTree       = window['AscDFH'].historyitem_type_Slide | 12;
	window['AscDFH'].historyitem_SlideSetCSldName       = window['AscDFH'].historyitem_type_Slide | 13;
	window['AscDFH'].historyitem_SlideSetClrMapOverride = window['AscDFH'].historyitem_type_Slide | 14;
	window['AscDFH'].historyitem_SlideSetNotes          = window['AscDFH'].historyitem_type_Slide | 15;

	window['AscDFH'].historyitem_SlideLayoutSetMaster         = window['AscDFH'].historyitem_type_SlideLayout | 1;
	window['AscDFH'].historyitem_SlideLayoutSetMatchingName   = window['AscDFH'].historyitem_type_SlideLayout | 2;
	window['AscDFH'].historyitem_SlideLayoutSetType           = window['AscDFH'].historyitem_type_SlideLayout | 3;
	window['AscDFH'].historyitem_SlideLayoutSetBg             = window['AscDFH'].historyitem_type_SlideLayout | 4;
	window['AscDFH'].historyitem_SlideLayoutSetCSldName       = window['AscDFH'].historyitem_type_SlideLayout | 5;
	window['AscDFH'].historyitem_SlideLayoutSetShow           = window['AscDFH'].historyitem_type_SlideLayout | 6;
	window['AscDFH'].historyitem_SlideLayoutSetShowPhAnim     = window['AscDFH'].historyitem_type_SlideLayout | 7;
	window['AscDFH'].historyitem_SlideLayoutSetShowMasterSp   = window['AscDFH'].historyitem_type_SlideLayout | 8;
	window['AscDFH'].historyitem_SlideLayoutSetClrMapOverride = window['AscDFH'].historyitem_type_SlideLayout | 9;
	window['AscDFH'].historyitem_SlideLayoutAddToSpTree       = window['AscDFH'].historyitem_type_SlideLayout | 10;
	window['AscDFH'].historyitem_SlideLayoutSetSize           = window['AscDFH'].historyitem_type_SlideLayout | 11;

	window['AscDFH'].historyitem_SlideMasterAddToSpTree       = window['AscDFH'].historyitem_type_SlideMaster | 1;
	window['AscDFH'].historyitem_SlideMasterSetTheme          = window['AscDFH'].historyitem_type_SlideMaster | 2;
	window['AscDFH'].historyitem_SlideMasterSetBg             = window['AscDFH'].historyitem_type_SlideMaster | 3;
	window['AscDFH'].historyitem_SlideMasterSetTxStyles       = window['AscDFH'].historyitem_type_SlideMaster | 4;
	window['AscDFH'].historyitem_SlideMasterSetCSldName       = window['AscDFH'].historyitem_type_SlideMaster | 5;
	window['AscDFH'].historyitem_SlideMasterSetClrMapOverride = window['AscDFH'].historyitem_type_SlideMaster | 6;
	window['AscDFH'].historyitem_SlideMasterAddLayout         = window['AscDFH'].historyitem_type_SlideMaster | 7;
	window['AscDFH'].historyitem_SlideMasterSetThemeIndex     = window['AscDFH'].historyitem_type_SlideMaster | 8;
	window['AscDFH'].historyitem_SlideMasterSetSize           = window['AscDFH'].historyitem_type_SlideMaster | 9;

	window['AscDFH'].historyitem_SlideCommentsAddComment    = window['AscDFH'].historyitem_type_SlideComments | 1;
	window['AscDFH'].historyitem_SlideCommentsRemoveComment = window['AscDFH'].historyitem_type_SlideComments | 2;

	window['AscDFH'].historyitem_PropLockerSetId = window['AscDFH'].historyitem_type_PropLocker | 1;

	window['AscDFH'].historyitem_ThemeSetColorScheme     = window['AscDFH'].historyitem_type_Theme | 1;
	window['AscDFH'].historyitem_ThemeSetFontScheme      = window['AscDFH'].historyitem_type_Theme | 2;
	window['AscDFH'].historyitem_ThemeSetFmtScheme       = window['AscDFH'].historyitem_type_Theme | 3;
	window['AscDFH'].historyitem_ThemeSetName            = window['AscDFH'].historyitem_type_Theme | 4;
	window['AscDFH'].historyitem_ThemeSetIsThemeOverride = window['AscDFH'].historyitem_type_Theme | 5;
	window['AscDFH'].historyitem_ThemeSetSpDef           = window['AscDFH'].historyitem_type_Theme | 6;
	window['AscDFH'].historyitem_ThemeSetLnDef           = window['AscDFH'].historyitem_type_Theme | 7;
	window['AscDFH'].historyitem_ThemeSetTxDef           = window['AscDFH'].historyitem_type_Theme | 8;
	window['AscDFH'].historyitem_ThemeAddExtraClrScheme  = window['AscDFH'].historyitem_type_Theme | 9;

	window['AscDFH'].historyitem_GraphicFrameSetSpPr          = window['AscDFH'].historyitem_type_GraphicFrame | 1;
	window['AscDFH'].historyitem_GraphicFrameSetGraphicObject = window['AscDFH'].historyitem_type_GraphicFrame | 2;
	window['AscDFH'].historyitem_GraphicFrameSetSetNvSpPr     = window['AscDFH'].historyitem_type_GraphicFrame | 3;
	window['AscDFH'].historyitem_GraphicFrameSetSetParent     = window['AscDFH'].historyitem_type_GraphicFrame | 4;
	window['AscDFH'].historyitem_GraphicFrameSetSetGroup      = window['AscDFH'].historyitem_type_GraphicFrame | 5;


    window['AscDFH'].historyitem_Sparkline_Type = window['AscDFH'].historyitem_type_Sparkline | 1;
    window['AscDFH'].historyitem_Sparkline_LineWeight = window['AscDFH'].historyitem_type_Sparkline | 2;
    window['AscDFH'].historyitem_Sparkline_DisplayEmptyCellsAs = window['AscDFH'].historyitem_type_Sparkline | 3;
    window['AscDFH'].historyitem_Sparkline_Markers = window['AscDFH'].historyitem_type_Sparkline | 4;
    window['AscDFH'].historyitem_Sparkline_High = window['AscDFH'].historyitem_type_Sparkline | 5;
    window['AscDFH'].historyitem_Sparkline_Low = window['AscDFH'].historyitem_type_Sparkline | 6;
    window['AscDFH'].historyitem_Sparkline_First = window['AscDFH'].historyitem_type_Sparkline | 7;
    window['AscDFH'].historyitem_Sparkline_Last = window['AscDFH'].historyitem_type_Sparkline | 8;
    window['AscDFH'].historyitem_Sparkline_Negative = window['AscDFH'].historyitem_type_Sparkline | 9;
    window['AscDFH'].historyitem_Sparkline_DisplayXAxis = window['AscDFH'].historyitem_type_Sparkline | 10;
    window['AscDFH'].historyitem_Sparkline_DisplayHidden = window['AscDFH'].historyitem_type_Sparkline | 11;
    window['AscDFH'].historyitem_Sparkline_MinAxisType = window['AscDFH'].historyitem_type_Sparkline | 12;
    window['AscDFH'].historyitem_Sparkline_MaxAxisType = window['AscDFH'].historyitem_type_Sparkline | 13;
    window['AscDFH'].historyitem_Sparkline_RightToLeft = window['AscDFH'].historyitem_type_Sparkline | 14;
    window['AscDFH'].historyitem_Sparkline_ManualMax = window['AscDFH'].historyitem_type_Sparkline | 15;
    window['AscDFH'].historyitem_Sparkline_ManualMin = window['AscDFH'].historyitem_type_Sparkline | 16;
    window['AscDFH'].historyitem_Sparkline_DateAxis = window['AscDFH'].historyitem_type_Sparkline | 17;
    window['AscDFH'].historyitem_Sparkline_ColorSeries = window['AscDFH'].historyitem_type_Sparkline | 18;
    window['AscDFH'].historyitem_Sparkline_ColorNegative = window['AscDFH'].historyitem_type_Sparkline | 19;
    window['AscDFH'].historyitem_Sparkline_ColorAxis = window['AscDFH'].historyitem_type_Sparkline | 20;
    window['AscDFH'].historyitem_Sparkline_ColorMarkers = window['AscDFH'].historyitem_type_Sparkline | 21;
    window['AscDFH'].historyitem_Sparkline_ColorFirst = window['AscDFH'].historyitem_type_Sparkline | 22;
    window['AscDFH'].historyitem_Sparkline_colorLast = window['AscDFH'].historyitem_type_Sparkline | 23;
    window['AscDFH'].historyitem_Sparkline_ColorHigh = window['AscDFH'].historyitem_type_Sparkline | 24;
    window['AscDFH'].historyitem_Sparkline_ColorLow = window['AscDFH'].historyitem_type_Sparkline | 25;
    window['AscDFH'].historyitem_Sparkline_F = window['AscDFH'].historyitem_type_Sparkline | 26;
    window['AscDFH'].historyitem_Sparkline_ChangeData = window['AscDFH'].historyitem_type_Sparkline | 27;
    window['AscDFH'].historyitem_Sparkline_RemoveData = window['AscDFH'].historyitem_type_Sparkline | 28;
    window['AscDFH'].historyitem_Sparkline_RemoveSparkline = window['AscDFH'].historyitem_type_Sparkline | 29;

	window['AscDFH'].historyitem_PivotTableDefinitionDelete = window['AscDFH'].historyitem_type_PivotTableDefinition | 1;


    window['AscDFH'].historyitem_NotesMasterSetHF          = window['AscDFH'].historyitem_type_NotesMaster | 1;
    window['AscDFH'].historyitem_NotesMasterSetNotesStyle  = window['AscDFH'].historyitem_type_NotesMaster | 2;
    window['AscDFH'].historyitem_NotesMasterSetNotesTheme  = window['AscDFH'].historyitem_type_NotesMaster | 3;
    window['AscDFH'].historyitem_NotesMasterAddToSpTree    = window['AscDFH'].historyitem_type_NotesMaster | 4;
    window['AscDFH'].historyitem_NotesMasterRemoveFromTree = window['AscDFH'].historyitem_type_NotesMaster | 5;
    window['AscDFH'].historyitem_NotesMasterSetBg          = window['AscDFH'].historyitem_type_NotesMaster | 6;
    window['AscDFH'].historyitem_NotesMasterAddToNotesLst  = window['AscDFH'].historyitem_type_NotesMaster | 7;
    window['AscDFH'].historyitem_NotesMasterSetName        = window['AscDFH'].historyitem_type_NotesMaster | 8;


    window['AscDFH'].historyitem_NotesSetClrMap           = window['AscDFH'].historyitem_type_Notes | 1;
    window['AscDFH'].historyitem_NotesSetShowMasterPhAnim = window['AscDFH'].historyitem_type_Notes | 2;
    window['AscDFH'].historyitem_NotesSetShowMasterSp     = window['AscDFH'].historyitem_type_Notes | 3;
    window['AscDFH'].historyitem_NotesAddToSpTree         = window['AscDFH'].historyitem_type_Notes | 4;
    window['AscDFH'].historyitem_NotesRemoveFromTree      = window['AscDFH'].historyitem_type_Notes | 5;
    window['AscDFH'].historyitem_NotesSetBg               = window['AscDFH'].historyitem_type_Notes | 6;
    window['AscDFH'].historyitem_NotesSetName             = window['AscDFH'].historyitem_type_Notes | 7;
    window['AscDFH'].historyitem_NotesSetSlide            = window['AscDFH'].historyitem_type_Notes | 8;
    window['AscDFH'].historyitem_NotesSetNotesMaster      = window['AscDFH'].historyitem_type_Notes | 9;

    window['AscDFH'].historyitem_PresentationSectionSetName       = window['AscDFH'].historyitem_type_PresentationSection | 1;
    window['AscDFH'].historyitem_PresentationSectionSetGuid       = window['AscDFH'].historyitem_type_PresentationSection | 2;
    window['AscDFH'].historyitem_PresentationSectionSetStartIndex = window['AscDFH'].historyitem_type_PresentationSection | 3;


	//------------------------------------------------------------------------------------------------------------------
	// Типы изменений класса CDocumentMacros
	//------------------------------------------------------------------------------------------------------------------
	window['AscDFH'].historyitem_DocumentMacros_Data = window['Asc'].historyitem_type_DocumentMacros | 1;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Типы действий, который может совершить пользователь
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].historydescription_Cut                                         = 0x0001;
	window['AscDFH'].historydescription_PasteButtonIE                               = 0x0002;
	window['AscDFH'].historydescription_PasteButtonNotIE                            = 0x0003;
	window['AscDFH'].historydescription_ChartDrawingObjects                         = 0x0004;
	window['AscDFH'].historydescription_CommonControllerCheckChartText              = 0x0005;
	window['AscDFH'].historydescription_CommonControllerUnGroup                     = 0x0006;
	window['AscDFH'].historydescription_CommonControllerCheckSelected               = 0x0007;
	window['AscDFH'].historydescription_CommonControllerSetGraphicObject            = 0x0008;
	window['AscDFH'].historydescription_CommonStatesAddNewShape                     = 0x0009;
	window['AscDFH'].historydescription_CommonStatesRotate                          = 0x000a;
	window['AscDFH'].historydescription_PasteNative                                 = 0x000b;
	window['AscDFH'].historydescription_Document_GroupUnGroup                       = 0x000c;
	window['AscDFH'].historydescription_Document_SetDefaultLanguage                 = 0x000d;
	window['AscDFH'].historydescription_Document_ChangeColorScheme                  = 0x000e;
	window['AscDFH'].historydescription_Document_AddChart                           = 0x000f;
	window['AscDFH'].historydescription_Document_EditChart                          = 0x0010;
	window['AscDFH'].historydescription_Document_DragText                           = 0x0011;
	window['AscDFH'].historydescription_Document_DocumentContentExtendToPos         = 0x0012;
	window['AscDFH'].historydescription_Document_AddHeader                          = 0x0013;
	window['AscDFH'].historydescription_Document_AddFooter                          = 0x0014;
	window['AscDFH'].historydescription_Document_ParagraphExtendToPos               = 0x0015;
	window['AscDFH'].historydescription_Document_ParagraphChangeFrame               = 0x0016;
	window['AscDFH'].historydescription_Document_ReplaceAll                         = 0x0017;
	window['AscDFH'].historydescription_Document_ReplaceSingle                      = 0x0018;
	window['AscDFH'].historydescription_Document_TableAddNewRowByTab                = 0x0019;
	window['AscDFH'].historydescription_Document_AddNewShape                        = 0x001a;
	window['AscDFH'].historydescription_Document_EditWrapPolygon                    = 0x001b;
	window['AscDFH'].historydescription_Document_MoveInlineObject                   = 0x001c;
	window['AscDFH'].historydescription_Document_CopyAndMoveInlineObject            = 0x001d;
	window['AscDFH'].historydescription_Document_RotateInlineDrawing                = 0x001e;
	window['AscDFH'].historydescription_Document_RotateFlowDrawingCtrl              = 0x001f;
	window['AscDFH'].historydescription_Document_RotateFlowDrawingNoCtrl            = 0x0020;
	window['AscDFH'].historydescription_Document_MoveInGroup                        = 0x0021;
	window['AscDFH'].historydescription_Document_ChangeWrapContour                  = 0x0022;
	window['AscDFH'].historydescription_Document_ChangeWrapContourAddPoint          = 0x0023;
	window['AscDFH'].historydescription_Document_GrObjectsBringToFront              = 0x0024;
	window['AscDFH'].historydescription_Document_GrObjectsBringForwardGroup         = 0x0025;
	window['AscDFH'].historydescription_Document_GrObjectsBringForward              = 0x0026;
	window['AscDFH'].historydescription_Document_GrObjectsSendToBackGroup           = 0x0027;
	window['AscDFH'].historydescription_Document_GrObjectsSendToBack                = 0x0028;
	window['AscDFH'].historydescription_Document_GrObjectsBringBackwardGroup        = 0x0029;
	window['AscDFH'].historydescription_Document_GrObjectsBringBackward             = 0x002a;
	window['AscDFH'].historydescription_Document_GrObjectsChangeWrapPolygon         = 0x002b;
	window['AscDFH'].historydescription_Document_MathAutoCorrect                    = 0x002c;
	window['AscDFH'].historydescription_Document_SetFramePrWithFontFamily           = 0x002d;
	window['AscDFH'].historydescription_Document_SetFramePr                         = 0x002e;
	window['AscDFH'].historydescription_Document_SetFramePrWithFontFamilyLong       = 0x002f;
	window['AscDFH'].historydescription_Document_SetTextFontName                    = 0x0030;
	window['AscDFH'].historydescription_Document_SetTextFontSize                    = 0x0031;
	window['AscDFH'].historydescription_Document_SetTextBold                        = 0x0032;
	window['AscDFH'].historydescription_Document_SetTextItalic                      = 0x0033;
	window['AscDFH'].historydescription_Document_SetTextUnderline                   = 0x0034;
	window['AscDFH'].historydescription_Document_SetTextStrikeout                   = 0x0035;
	window['AscDFH'].historydescription_Document_SetTextDStrikeout                  = 0x0036;
	window['AscDFH'].historydescription_Document_SetTextSpacing                     = 0x0037;
	window['AscDFH'].historydescription_Document_SetTextCaps                        = 0x0038;
	window['AscDFH'].historydescription_Document_SetTextSmallCaps                   = 0x0039;
	window['AscDFH'].historydescription_Document_SetTextPosition                    = 0x003a;
	window['AscDFH'].historydescription_Document_SetTextLang                        = 0x003b;
	window['AscDFH'].historydescription_Document_SetParagraphLineSpacing            = 0x003c;
	window['AscDFH'].historydescription_Document_SetParagraphLineSpacingBeforeAfter = 0x003d;
	window['AscDFH'].historydescription_Document_IncFontSize                        = 0x003e;
	window['AscDFH'].historydescription_Document_DecFontSize                        = 0x003f;
	window['AscDFH'].historydescription_Document_SetParagraphBorders                = 0x0040;
	window['AscDFH'].historydescription_Document_SetParagraphPr                     = 0x0041;
	window['AscDFH'].historydescription_Document_SetParagraphAlign                  = 0x0042;
	window['AscDFH'].historydescription_Document_SetTextVertAlign                   = 0x0043;
	window['AscDFH'].historydescription_Document_SetParagraphNumbering              = 0x0044;
	window['AscDFH'].historydescription_Document_SetParagraphStyle                  = 0x0045;
	window['AscDFH'].historydescription_Document_SetParagraphPageBreakBefore        = 0x0046;
	window['AscDFH'].historydescription_Document_SetParagraphWidowControl           = 0x0047;
	window['AscDFH'].historydescription_Document_SetParagraphKeepLines              = 0x0048;
	window['AscDFH'].historydescription_Document_SetParagraphKeepNext               = 0x0049;
	window['AscDFH'].historydescription_Document_SetParagraphContextualSpacing      = 0x004a;
	window['AscDFH'].historydescription_Document_SetTextHighlightNone               = 0x004b;
	window['AscDFH'].historydescription_Document_SetTextHighlightColor              = 0x004c;
	window['AscDFH'].historydescription_Document_SetTextColor                       = 0x004d;
	window['AscDFH'].historydescription_Document_SetParagraphShd                    = 0x004e;
	window['AscDFH'].historydescription_Document_SetParagraphIndent                 = 0x004f;
	window['AscDFH'].historydescription_Document_IncParagraphIndent                 = 0x0050;
	window['AscDFH'].historydescription_Document_DecParagraphIndent                 = 0x0051;
	window['AscDFH'].historydescription_Document_SetParagraphIndentRight            = 0x0052;
	window['AscDFH'].historydescription_Document_SetParagraphIndentFirstLine        = 0x0053;
	window['AscDFH'].historydescription_Document_SetPageOrientation                 = 0x0054;
	window['AscDFH'].historydescription_Document_SetPageSize                        = 0x0055;
	window['AscDFH'].historydescription_Document_AddPageBreak                       = 0x0056;
	window['AscDFH'].historydescription_Document_AddPageNumToHdrFtr                 = 0x0057;
	window['AscDFH'].historydescription_Document_AddPageNumToCurrentPos             = 0x0058;
	window['AscDFH'].historydescription_Document_SetHdrFtrDistance                  = 0x0059;
	window['AscDFH'].historydescription_Document_SetHdrFtrFirstPage                 = 0x005a;
	window['AscDFH'].historydescription_Document_SetHdrFtrEvenAndOdd                = 0x005b;
	window['AscDFH'].historydescription_Document_SetHdrFtrLink                      = 0x005c;
	window['AscDFH'].historydescription_Document_AddTable                           = 0x005d;
	window['AscDFH'].historydescription_Document_TableAddRowAbove                   = 0x005e;
	window['AscDFH'].historydescription_Document_TableAddRowBelow                   = 0x005f;
	window['AscDFH'].historydescription_Document_TableAddColumnLeft                 = 0x0060;
	window['AscDFH'].historydescription_Document_TableAddColumnRight                = 0x0061;
	window['AscDFH'].historydescription_Document_TableRemoveRow                     = 0x0062;
	window['AscDFH'].historydescription_Document_TableRemoveColumn                  = 0x0063;
	window['AscDFH'].historydescription_Document_RemoveTable                        = 0x0064;
	window['AscDFH'].historydescription_Document_MergeTableCells                    = 0x0065;
	window['AscDFH'].historydescription_Document_SplitTableCells                    = 0x0066;
	window['AscDFH'].historydescription_Document_ApplyTablePr                       = 0x0067;
	window['AscDFH'].historydescription_Document_AddImageUrl                        = 0x0068;
	window['AscDFH'].historydescription_Document_AddImageUrlLong                    = 0x0069;
	window['AscDFH'].historydescription_Document_AddImageToPage                     = 0x006a;
	window['AscDFH'].historydescription_Document_ApplyImagePrWithUrl                = 0x006b;
	window['AscDFH'].historydescription_Document_ApplyImagePrWithUrlLong            = 0x006c;
	window['AscDFH'].historydescription_Document_ApplyImagePrWithFillUrl            = 0x006d;
	window['AscDFH'].historydescription_Document_ApplyImagePrWithFillUrlLong        = 0x006e;
	window['AscDFH'].historydescription_Document_ApplyImagePr                       = 0x006f;
	window['AscDFH'].historydescription_Document_AddHyperlink                       = 0x0070;
	window['AscDFH'].historydescription_Document_ChangeHyperlink                    = 0x0071;
	window['AscDFH'].historydescription_Document_RemoveHyperlink                    = 0x0072;
	window['AscDFH'].historydescription_Document_ReplaceMisspelledWord              = 0x0073;
	window['AscDFH'].historydescription_Document_AddComment                         = 0x0074;
	window['AscDFH'].historydescription_Document_RemoveComment                      = 0x0075;
	window['AscDFH'].historydescription_Document_ChangeComment                      = 0x0076;
	window['AscDFH'].historydescription_Document_SetTextFontNameLong                = 0x0077;
	window['AscDFH'].historydescription_Document_AddImage                           = 0x0078;
	window['AscDFH'].historydescription_Document_ClearFormatting                    = 0x0079;
	window['AscDFH'].historydescription_Document_AddSectionBreak                    = 0x007a;
	window['AscDFH'].historydescription_Document_AddMath                            = 0x007b;
	window['AscDFH'].historydescription_Document_SetParagraphTabs                   = 0x007c;
	window['AscDFH'].historydescription_Document_SetParagraphIndentFromRulers       = 0x007d;
	window['AscDFH'].historydescription_Document_SetDocumentMargin_Hor              = 0x007e;
	window['AscDFH'].historydescription_Document_SetTableMarkup_Hor                 = 0x007f;
	window['AscDFH'].historydescription_Document_SetDocumentMargin_Ver              = 0x0080;
	window['AscDFH'].historydescription_Document_SetHdrFtrBounds                    = 0x0081;
	window['AscDFH'].historydescription_Document_SetTableMarkup_Ver                 = 0x0082;
	window['AscDFH'].historydescription_Document_DocumentExtendToPos                = 0x0083;
	window['AscDFH'].historydescription_Document_AddDropCap                         = 0x0084;
	window['AscDFH'].historydescription_Document_RemoveDropCap                      = 0x0085;
	window['AscDFH'].historydescription_Document_SetTextHighlight                   = 0x0086;
	window['AscDFH'].historydescription_Document_BackSpaceButton                    = 0x0087;
	window['AscDFH'].historydescription_Document_MoveParagraphByTab                 = 0x0088;
	window['AscDFH'].historydescription_Document_AddTab                             = 0x0089;
	window['AscDFH'].historydescription_Document_EnterButton                        = 0x008a;
	window['AscDFH'].historydescription_Document_SpaceButton                        = 0x008b;
	window['AscDFH'].historydescription_Document_ShiftInsert                        = 0x008c;
	window['AscDFH'].historydescription_Document_ShiftInsertSafari                  = 0x008d;
	window['AscDFH'].historydescription_Document_DeleteButton                       = 0x008e;
	window['AscDFH'].historydescription_Document_ShiftDeleteButton                  = 0x008f;
	window['AscDFH'].historydescription_Document_SetStyleHeading1                   = 0x0090;
	window['AscDFH'].historydescription_Document_SetStyleHeading2                   = 0x0091;
	window['AscDFH'].historydescription_Document_SetStyleHeading3                   = 0x0092;
	window['AscDFH'].historydescription_Document_SetTextStrikeoutHotKey             = 0x0093;
	window['AscDFH'].historydescription_Document_SetTextBoldHotKey                  = 0x0094;
	window['AscDFH'].historydescription_Document_SetParagraphAlignHotKey            = 0x0095;
	window['AscDFH'].historydescription_Document_AddEuroLetter                      = 0x0096;
	window['AscDFH'].historydescription_Document_SetTextItalicHotKey                = 0x0097;
	window['AscDFH'].historydescription_Document_SetParagraphAlignHotKey2           = 0x0098;
	window['AscDFH'].historydescription_Document_SetParagraphNumberingHotKey        = 0x0099;
	window['AscDFH'].historydescription_Document_SetParagraphAlignHotKey3           = 0x009a;
	window['AscDFH'].historydescription_Document_AddPageNumHotKey                   = 0x009b;
	window['AscDFH'].historydescription_Document_SetParagraphAlignHotKey4           = 0x009c;
	window['AscDFH'].historydescription_Document_SetTextUnderlineHotKey             = 0x009d;
	window['AscDFH'].historydescription_Document_FormatPasteHotKey                  = 0x009e;
	window['AscDFH'].historydescription_Document_PasteHotKey                        = 0x009f;
	window['AscDFH'].historydescription_Document_PasteSafariHotKey                  = 0x00a0;
	window['AscDFH'].historydescription_Document_CutHotKey                          = 0x00a1;
	window['AscDFH'].historydescription_Document_SetTextVertAlignHotKey             = 0x00a2;
	window['AscDFH'].historydescription_Document_AddMathHotKey                      = 0x00a3;
	window['AscDFH'].historydescription_Document_SetTextVertAlignHotKey2            = 0x00a4;
	window['AscDFH'].historydescription_Document_MinusButton                        = 0x00a5;
	window['AscDFH'].historydescription_Document_SetTextVertAlignHotKey3            = 0x00a6;
	window['AscDFH'].historydescription_Document_AddLetter                          = 0x00a7;
	window['AscDFH'].historydescription_Document_MoveTableBorder                    = 0x00a8;
	window['AscDFH'].historydescription_Document_FormatPasteHotKey2                 = 0x00a9;
	window['AscDFH'].historydescription_Document_SetTextHighlight2                  = 0x00aa;
	window['AscDFH'].historydescription_Document_AddTextFromTextBox                 = 0x00ab;
	window['AscDFH'].historydescription_Document_AddMailMergeField                  = 0x00ac;
	window['AscDFH'].historydescription_Document_MoveInlineTable                    = 0x00ad;
	window['AscDFH'].historydescription_Document_MoveFlowTable                      = 0x00ae;
	window['AscDFH'].historydescription_Document_RestoreFieldTemplateText           = 0x00af;
	window['AscDFH'].historydescription_Spreadsheet_SetCellFontName                 = 0x00b0;
	window['AscDFH'].historydescription_Spreadsheet_SetCellFontSize                 = 0x00b1;
	window['AscDFH'].historydescription_Spreadsheet_SetCellBold                     = 0x00b2;
	window['AscDFH'].historydescription_Spreadsheet_SetCellItalic                   = 0x00b3;
	window['AscDFH'].historydescription_Spreadsheet_SetCellUnderline                = 0x00b4;
	window['AscDFH'].historydescription_Spreadsheet_SetCellStrikeout                = 0x00b5;
	window['AscDFH'].historydescription_Spreadsheet_SetCellSubscript                = 0x00b6;
	window['AscDFH'].historydescription_Spreadsheet_SetCellSuperscript              = 0x00b7;
	window['AscDFH'].historydescription_Spreadsheet_SetCellAlign                    = 0x00b8;
	window['AscDFH'].historydescription_Spreadsheet_SetCellVertAlign                = 0x00b9;
	window['AscDFH'].historydescription_Spreadsheet_SetCellTextColor                = 0x00ba;
	window['AscDFH'].historydescription_Spreadsheet_SetCellBackgroundColor          = 0x00bb;
	window['AscDFH'].historydescription_Spreadsheet_SetCellIncreaseFontSize         = 0x00bc;
	window['AscDFH'].historydescription_Spreadsheet_SetCellDecreaseFontSize         = 0x00bd;
	window['AscDFH'].historydescription_Spreadsheet_SetCellHyperlinkAdd             = 0x00be;
	window['AscDFH'].historydescription_Spreadsheet_SetCellHyperlinkModify          = 0x00bf;
	window['AscDFH'].historydescription_Spreadsheet_SetCellHyperlinkRemove          = 0x00c0;
	window['AscDFH'].historydescription_Spreadsheet_EditChart                       = 0x00c1;
	window['AscDFH'].historydescription_Spreadsheet_Remove                          = 0x00c2;
	window['AscDFH'].historydescription_Spreadsheet_AddTab                          = 0x00c3;
	window['AscDFH'].historydescription_Spreadsheet_AddNewParagraph                 = 0x00c4;
	window['AscDFH'].historydescription_Spreadsheet_AddSpace                        = 0x00c5;
	window['AscDFH'].historydescription_Spreadsheet_AddItem                         = 0x00c6;
	window['AscDFH'].historydescription_Spreadsheet_PutPrLineSpacing                = 0x00c7;
	window['AscDFH'].historydescription_Spreadsheet_SetParagraphSpacing             = 0x00c8;
	window['AscDFH'].historydescription_Spreadsheet_SetGraphicObjectsProps          = 0x00c9;
	window['AscDFH'].historydescription_Spreadsheet_ParaApply                       = 0x00ca;
	window['AscDFH'].historydescription_Spreadsheet_GraphicObjectLayer              = 0x00cb;
	window['AscDFH'].historydescription_Spreadsheet_ParagraphAdd                    = 0x00cc;
	window['AscDFH'].historydescription_Spreadsheet_CreateGroup                     = 0x00cd;
	window['AscDFH'].historydescription_CommonDrawings_ChangeAdj                    = 0x00ce;
	window['AscDFH'].historydescription_CommonDrawings_EndTrack                     = 0x00cf;
	window['AscDFH'].historydescription_CommonDrawings_CopyCtrl                     = 0x00d0;
	window['AscDFH'].historydescription_Presentation_ParaApply                      = 0x00d1;
	window['AscDFH'].historydescription_Presentation_ParaFormatPaste                = 0x00d2;
	window['AscDFH'].historydescription_Presentation_AddNewParagraph                = 0x00d3;
	window['AscDFH'].historydescription_Presentation_CreateGroup                    = 0x00d4;
	window['AscDFH'].historydescription_Presentation_UnGroup                        = 0x00d5;
	window['AscDFH'].historydescription_Presentation_AddChart                       = 0x00d6;
	window['AscDFH'].historydescription_Presentation_EditChart                      = 0x00d7;
	window['AscDFH'].historydescription_Presentation_ParagraphAdd                   = 0x00d8;
	window['AscDFH'].historydescription_Presentation_ParagraphClearFormatting       = 0x00d9;
	window['AscDFH'].historydescription_Presentation_SetParagraphAlign              = 0x00da;
	window['AscDFH'].historydescription_Presentation_SetParagraphSpacing            = 0x00db;
	window['AscDFH'].historydescription_Presentation_SetParagraphTabs               = 0x00dc;
	window['AscDFH'].historydescription_Presentation_SetParagraphIndent             = 0x00dd;
	window['AscDFH'].historydescription_Presentation_SetParagraphNumbering          = 0x00de;
	window['AscDFH'].historydescription_Presentation_ParagraphIncDecFontSize        = 0x00df;
	window['AscDFH'].historydescription_Presentation_ParagraphIncDecIndent          = 0x00e0;
	window['AscDFH'].historydescription_Presentation_SetImageProps                  = 0x00e1;
	window['AscDFH'].historydescription_Presentation_SetShapeProps                  = 0x00e2;
	window['AscDFH'].historydescription_Presentation_ChartApply                     = 0x00e3;
	window['AscDFH'].historydescription_Presentation_ChangeShapeType                = 0x00e4;
	window['AscDFH'].historydescription_Presentation_SetVerticalAlign               = 0x00e5;
	window['AscDFH'].historydescription_Presentation_HyperlinkAdd                   = 0x00e6;
	window['AscDFH'].historydescription_Presentation_HyperlinkModify                = 0x00e7;
	window['AscDFH'].historydescription_Presentation_HyperlinkRemove                = 0x00e8;
	window['AscDFH'].historydescription_Presentation_DistHor                        = 0x00e9;
	window['AscDFH'].historydescription_Presentation_DistVer                        = 0x00ea;
	window['AscDFH'].historydescription_Presentation_BringToFront                   = 0x00eb;
	window['AscDFH'].historydescription_Presentation_BringForward                   = 0x00ec;
	window['AscDFH'].historydescription_Presentation_SendToBack                     = 0x00ed;
	window['AscDFH'].historydescription_Presentation_BringBackward                  = 0x00ef;
	window['AscDFH'].historydescription_Presentation_ApplyTiming                    = 0x00f0;
	window['AscDFH'].historydescription_Presentation_MoveSlidesToEnd                = 0x00f1;
	window['AscDFH'].historydescription_Presentation_MoveSlidesNextPos              = 0x00f2;
	window['AscDFH'].historydescription_Presentation_MoveSlidesPrevPos              = 0x00f3;
	window['AscDFH'].historydescription_Presentation_MoveSlidesToStart              = 0x00f4;
	window['AscDFH'].historydescription_Presentation_MoveComments                   = 0x00f5;
	window['AscDFH'].historydescription_Presentation_TableBorder                    = 0x00f6;
	window['AscDFH'].historydescription_Presentation_AddFlowImage                   = 0x00f7;
	window['AscDFH'].historydescription_Presentation_AddFlowTable                   = 0x00f8;
	window['AscDFH'].historydescription_Presentation_ChangeBackground               = 0x00f9;
	window['AscDFH'].historydescription_Presentation_AddNextSlide                   = 0x00fa;
	window['AscDFH'].historydescription_Presentation_ShiftSlides                    = 0x00fb;
	window['AscDFH'].historydescription_Presentation_DeleteSlides                   = 0x00fc;
	window['AscDFH'].historydescription_Presentation_ChangeLayout                   = 0x00fd;
	window['AscDFH'].historydescription_Presentation_ChangeSlideSize                = 0x00fe;
	window['AscDFH'].historydescription_Presentation_ChangeColorScheme              = 0x00ff;
	window['AscDFH'].historydescription_Presentation_AddComment                     = 0x0100;
	window['AscDFH'].historydescription_Presentation_ChangeComment                  = 0x0101;
	window['AscDFH'].historydescription_Presentation_PutTextPrFontName              = 0x0102;
	window['AscDFH'].historydescription_Presentation_PutTextPrFontSize              = 0x0103;
	window['AscDFH'].historydescription_Presentation_PutTextPrBold                  = 0x0104;
	window['AscDFH'].historydescription_Presentation_PutTextPrItalic                = 0x0105;
	window['AscDFH'].historydescription_Presentation_PutTextPrUnderline             = 0x0106;
	window['AscDFH'].historydescription_Presentation_PutTextPrStrikeout             = 0x0107;
	window['AscDFH'].historydescription_Presentation_PutTextPrLineSpacing           = 0x0108;
	window['AscDFH'].historydescription_Presentation_PutTextPrSpacingBeforeAfter    = 0x0109;
	window['AscDFH'].historydescription_Presentation_PutTextPrIncreaseFontSize      = 0x010a;
	window['AscDFH'].historydescription_Presentation_PutTextPrDecreaseFontSize      = 0x010b;
	window['AscDFH'].historydescription_Presentation_PutTextPrAlign                 = 0x010c;
	window['AscDFH'].historydescription_Presentation_PutTextPrBaseline              = 0x010d;
	window['AscDFH'].historydescription_Presentation_PutTextPrListType              = 0x010e;
	window['AscDFH'].historydescription_Presentation_PutTextColor                   = 0x010f;
	window['AscDFH'].historydescription_Presentation_PutTextColor2                  = 0x010f;
	window['AscDFH'].historydescription_Presentation_PutPrIndent                    = 0x010f;
	window['AscDFH'].historydescription_Presentation_PutPrIndentRight               = 0x010f;
	window['AscDFH'].historydescription_Presentation_PutPrFirstLineIndent           = 0x010f;
	window['AscDFH'].historydescription_Presentation_AddPageBreak                   = 0x010f;
	window['AscDFH'].historydescription_Presentation_AddRowAbove                    = 0x0110;
	window['AscDFH'].historydescription_Presentation_AddRowBelow                    = 0x0111;
	window['AscDFH'].historydescription_Presentation_AddColLeft                     = 0x0112;
	window['AscDFH'].historydescription_Presentation_AddColRight                    = 0x0113;
	window['AscDFH'].historydescription_Presentation_RemoveRow                      = 0x0114;
	window['AscDFH'].historydescription_Presentation_RemoveCol                      = 0x0115;
	window['AscDFH'].historydescription_Presentation_RemoveTable                    = 0x0116;
	window['AscDFH'].historydescription_Presentation_MergeCells                     = 0x0117;
	window['AscDFH'].historydescription_Presentation_SplitCells                     = 0x0118;
	window['AscDFH'].historydescription_Presentation_TblApply                       = 0x0119;
	window['AscDFH'].historydescription_Presentation_RemoveComment                  = 0x011a;
	window['AscDFH'].historydescription_Presentation_EndFontLoad                    = 0x011b;
	window['AscDFH'].historydescription_Presentation_ChangeTheme                    = 0x011c;
	window['AscDFH'].historydescription_Presentation_TableMoveFromRulers            = 0x011d;
	window['AscDFH'].historydescription_Presentation_TableMoveFromRulersInline      = 0x011e;
	window['AscDFH'].historydescription_Presentation_PasteOnThumbnails              = 0x011f;
	window['AscDFH'].historydescription_Presentation_PasteOnThumbnailsSafari        = 0x0120;
	window['AscDFH'].historydescription_Document_ConvertOldEquation                 = 0x0121;
	window['AscDFH'].historydescription_Presentation_SetVert                        = 0x0122;
	window['AscDFH'].historydescription_Document_AddNewStyle                        = 0x0123;
	window['AscDFH'].historydescription_Document_RemoveStyle                        = 0x0124;
	window['AscDFH'].historydescription_Document_AddTextArt                         = 0x0125;
	window['AscDFH'].historydescription_Document_RemoveAllCustomStyles              = 0x0126;
	window['AscDFH'].historydescription_Document_AcceptAllRevisionChanges           = 0x0127;
	window['AscDFH'].historydescription_Document_RejectAllRevisionChanges           = 0x0128;
	window['AscDFH'].historydescription_Document_AcceptRevisionChange               = 0x0129;
	window['AscDFH'].historydescription_Document_RejectRevisionChange               = 0x012a;
	window['AscDFH'].historydescription_Document_AcceptRevisionChangesBySelection   = 0x012b;
	window['AscDFH'].historydescription_Document_RejectRevisionChangesBySelection   = 0x012c;
	window['AscDFH'].historydescription_Document_AddLetterUnion                     = 0x012d;
	window['AscDFH'].historydescription_Presentation_ApplyTimingToAll               = 0x012e;
	window['AscDFH'].historydescription_Document_SetColumnsFromRuler                = 0x012f;
	window['AscDFH'].historydescription_Document_SetColumnsProps                    = 0x0130;
	window['AscDFH'].historydescription_Document_AddColumnBreak                     = 0x0131;
	window['AscDFH'].historydescription_Document_SetSectionProps                    = 0x0132;
	window['AscDFH'].historydescription_Document_AddTabToMath                       = 0x0133;
	window['AscDFH'].historydescription_Document_SetMathProps                       = 0x0134;
	window['AscDFH'].historydescription_Document_ApplyPrToMath                      = 0x0135;
	window['AscDFH'].historydescription_Document_ApiBuilder                         = 0x0136;
	window['AscDFH'].historydescription_Document_AddOleObject                       = 0x0137;
	window['AscDFH'].historydescription_Document_EditOleObject                      = 0x0138;
	window['AscDFH'].historydescription_Document_CompositeInput                     = 0x0139;
	window['AscDFH'].historydescription_Document_CompositeInputReplace              = 0x013a;
	window['AscDFH'].historydescription_Document_AddPageCount                       = 0x013b;
	window['AscDFH'].historydescription_Document_AddFootnote                        = 0x013c;
	window['AscDFH'].historydescription_Document_SetFootnotePr                      = 0x013d;
	window['AscDFH'].historydescription_Document_RemoveAllFootnotes                 = 0x013e;
	window['AscDFH'].historydescription_Document_InsertDocumentsByUrls              = 0x013f;
	window['AscDFH'].historydescription_Document_InsertSignatureLine                = 0x0140;
	window['AscDFH'].historydescription_Document_AddBlockLevelContentControl        = 0x0141;
	window['AscDFH'].historydescription_Document_AddInlineLevelContentControl       = 0x0142;
	window['AscDFH'].historydescription_Document_RemoveContentControl               = 0x0143;
	window['AscDFH'].historydescription_Document_RemoveContentControlWrapper        = 0x0144;
	window['AscDFH'].historydescription_Document_ChangeContentControlProperties     = 0x0145;
    window['AscDFH'].historydescription_Presentation_HideSlides                     = 0x0146;
	window['AscDFH'].historydescription_DocumentMacros_Data                         = 0x0147;
    window['AscDFH'].historydescription_Document_AddBookmark                        = 0x0148;
	window['AscDFH'].historydescription_Document_AddTableOfContents                 = 0x0149;
	window['AscDFH'].historydescription_Document_ChangeOutlineLevel                 = 0x014a;
	window['AscDFH'].historydescription_Document_AddElementToOutline                = 0x014b;
	window['AscDFH'].historydescription_Document_ResizeTable                        = 0x014c;
	window['AscDFH'].historydescription_Document_RemoveComplexField                 = 0x014d;
	window['AscDFH'].historydescription_Document_SetComplexFieldPr                  = 0x014e;
	window['AscDFH'].historydescription_Document_UpdateTableOfContents              = 0x014f;
	window['AscDFH'].historydescription_Document_SectionStartPage                   = 0x0150;
	window['AscDFH'].historydescription_Document_DistributeTableCells               = 0x0151;
	window['AscDFH'].historydescription_Document_RemoveBookmark                     = 0x0152;
	window['AscDFH'].historydescription_Document_ContinueNumbering                  = 0x0153;
	window['AscDFH'].historydescription_Document_RestartNumbering                   = 0x0154;
	window['AscDFH'].historydescription_Document_AutomaticListAsType                = 0x0155;
	window['AscDFH'].historydescription_Document_CreateNum                          = 0x0156;
	window['AscDFH'].historydescription_Document_ChangeNumLvl                       = 0x0157;
	window['AscDFH'].historydescription_Document_AutoCorrectSmartQuotes             = 0x0158;
	window['AscDFH'].historydescription_Document_AutoCorrectHyphensWithDash         = 0x0159;
	window['AscDFH'].historydescription_Document_SetGlobalSdtHighlightColor         = 0x015a;
	window['AscDFH'].historydescription_Document_SetGlobalSdtShowHighlight          = 0x015b;



	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Фабрика изменений (заполняется там же, где и определяются классы изменений)
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].changesFactory = {};
	window['AscDFH'].changesFactory[window['AscDFH'].historyitem_Unknown_Unknown] = CChangesBase;
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Карта зависимости изменений. Изменения зависят только от изменений для того же класса, но вот типы могут быть
	// разными. В основном изменения зависят только от изменений такого же типа.
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	window['AscDFH'].changesRelationMap = {};
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// Базовые классы для изменений
	//
	// Разница между классами Property и Value в том, что Property могут быть undefined, а Value всегда значение
	// заданного типа.
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * Базовый класс для всех изменений совместного редактирования.
	 * @constructor
	 */
	function CChangesBase(Class)
	{
		this.Class = Class;

		this.Reverted = false;
	}
	CChangesBase.prototype.Type = window['AscDFH'].historyitem_Unknown_Unknown;
	CChangesBase.prototype.Undo = function()
	{
		if (this.Class && this.Class.Undo)
			this.Class.Undo(this);
	};
	CChangesBase.prototype.Redo = function()
	{
		if (this.Class && this.Class.Redo)
			this.Class.Redo(this);
	};
	CChangesBase.prototype.WriteToBinary = function(Writer)
	{
		if (this.Class && this.Class.Save_Changes)
			this.Class.Save_Changes(this, Writer);
	};
	CChangesBase.prototype.ReadFromBinary = function(Reader)
	{

	};
	CChangesBase.prototype.Load = function()
	{
		// В большинстве случаев загрузка чужого изменения работает как простое Redo
		this.Redo();
	};
	CChangesBase.prototype.GetClass = function()
	{
		return this.Class;
	};
	CChangesBase.prototype.RefreshRecalcData = function()
	{
		if (this.Class && this.Class.Refresh_RecalcData)
			this.Class.Refresh_RecalcData(this);
	};
	CChangesBase.prototype.IsContentChange = function()
	{
		return false;
	};
	CChangesBase.prototype.CreateReverseChange = function()
	{
		return null;
	};
	CChangesBase.prototype.Merge = function(oChange)
	{
		return true;
	};
	CChangesBase.prototype.IsPosExtChange = function(oChange)
	{
		return false;
	};
	CChangesBase.prototype.IsReverted = function()
	{
		return this.Reverted;
	};
	CChangesBase.prototype.SetReverted = function(isReverted)
	{
		this.Reverted = isReverted;
	};
	CChangesBase.prototype.IsParagraphSimpleChanges = function()
	{
		return false;
	};
	window['AscDFH'].CChangesBase = CChangesBase;
	/**
	 * Базовый класс для изменений, которые меняют содержимое родительского класса.*
	 * @constructor
	 * @extends {AscDFH.CChangesBase}
	 */
	function CChangesBaseContentChange(Class, Pos, Items, isAdd)
	{
		CChangesBase.call(this, Class);

		this.Pos      = Pos;
		this.Items    = Items;
		this.UseArray = false;
		this.PosArray = [];
		this.Add      = isAdd;

		this.Reverted = false;
	}

	CChangesBaseContentChange.prototype = Object.create(CChangesBase.prototype);
	CChangesBaseContentChange.prototype.constructor = CChangesBaseContentChange;
	CChangesBaseContentChange.prototype.IsContentChange = function()
	{
		return true;
	};
	CChangesBaseContentChange.prototype.IsAdd = function()
	{
		return this.Add;
	};
	CChangesBaseContentChange.prototype.Copy = function()
	{
		var oChanges = new this.constructor(this.Class, this.Pos, this.Items, this.Add);

		oChanges.UseArray = this.UseArray;

		for (var nIndex = 0, nCount = this.PosArray.length; nIndex < nCount; ++nIndex)
			oChanges.PosArray[nIndex] = this.PosArray[nIndex];

		return oChanges;
	};
	CChangesBaseContentChange.prototype.GetItemsCount = function()
	{
		return this.Items.length;
	};
	CChangesBaseContentChange.prototype.WriteToBinary = function(Writer)
	{
		// Long : Количество элементов
		// Array of
		// {
		//    Long     : позиции элементов
		//    Variable : Item
		// }
		// Long : Поле Color

		var bArray = this.UseArray;
		var nCount = this.Items.length;

		var nStartPos = Writer.GetCurPosition();
		Writer.Skip(4);
		var nRealCount = nCount;

		for (var nIndex = 0; nIndex < nCount; ++nIndex)
		{
			if (true === bArray)
			{
				if (false === this.PosArray[nIndex])
				{
					nRealCount--;
				}
				else
				{
					Writer.WriteLong(this.PosArray[nIndex]);
					this.private_WriteItem(Writer, this.Items[nIndex]);
				}
			}
			else
			{
				Writer.WriteLong(this.Pos);
				this.private_WriteItem(Writer, this.Items[nIndex]);
			}
		}

		var nEndPos = Writer.GetCurPosition();
		Writer.Seek(nStartPos);
		Writer.WriteLong(nRealCount);
		Writer.Seek(nEndPos);

		var nColor = 0;
		if (undefined !== this.Color)
		{
			nColor |= 1;
			if (true === this.Color)
				nColor |= 2;
		}
		Writer.WriteLong(nColor);
	};
	CChangesBaseContentChange.prototype.ReadFromBinary = function(Reader)
	{
		// Long : Количество элементов
		// Array of
		// {
		//    Long     : позиции элементов
		//    Variable : Item
		// }
		// Long : поле Color

		this.UseArray = true;
		this.Items    = [];
		this.PosArray = [];

		var nCount = Reader.GetLong();
		for (var nIndex = 0; nIndex < nCount; ++nIndex)
		{
			this.PosArray[nIndex] = Reader.GetLong();
			this.Items[nIndex]    = this.private_ReadItem(Reader);
		}

		var nColor = Reader.GetLong();
		if (nColor & 1)
			this.Color = (nColor & 2) ? true : false;
	};
	CChangesBaseContentChange.prototype.private_WriteItem = function(Writer, Item)
	{
	};
	CChangesBaseContentChange.prototype.private_ReadItem = function(Reader)
	{
		return null;
	};
	CChangesBaseContentChange.prototype.ConvertToSimpleActions = function()
	{
		var arrActions = [];

		if (this.UseArray)
		{
			for (var nIndex = 0, nCount = this.Items.length; nIndex < nCount; ++nIndex)
			{
				arrActions.push({
					Item : this.Items[nIndex],
					Pos  : this.PosArray[nIndex],
					Add  : this.Add
				});
			}
		}
		else
		{
			var Pos = this.Pos;
			for (var nIndex = 0, nCount = this.Items.length; nIndex < nCount; ++nIndex)
			{
				arrActions.push({
					Item : this.Items[nIndex],
					Pos  : Pos + nIndex,
					Add  : this.Add
				});
			}
		}

		return arrActions;
	};
	CChangesBaseContentChange.prototype.ConvertFromSimpleActions = function(arrActions)
	{
		this.UseArray = true;
		this.Pos      = 0;
		this.Items    = [];
		this.PosArray = [];

		for (var nIndex = 0, nCount = arrActions.length; nIndex < nCount; ++nIndex)
		{
			this.PosArray[nIndex] = arrActions[nIndex].Pos;
			this.Items[nIndex]    = arrActions[nIndex].Item;
		}
	};
	CChangesBaseContentChange.prototype.IsRelated = function(oChanges)
	{
		if (this.Class !== oChanges.GetClass() || this.Type !== oChanges.Type)
			return false;

		return true;
	};
	CChangesBaseContentChange.prototype.private_CreateReverseChange = function(fConstructor)
	{
		var oChange = new fConstructor();

		oChange.Class    = this.Class;
		oChange.Pos      = this.Pos;
		oChange.Items    = this.Items;
		oChange.Add      = !this.Add;
		oChange.UseArray = this.UseArray;
		oChange.PosArray = [];

		for (var nIndex = 0, nCount = this.PosArray.length; nIndex < nCount; ++nIndex)
			oChange.PosArray[nIndex] = this.PosArray[nIndex];

		return oChange;
	};
	CChangesBaseContentChange.prototype.Merge = function(oChange)
	{
		// TODO: Сюда надо бы перенести работу с ContentChanges
		return true;
	};
	CChangesBaseContentChange.prototype.GetMinPos = function()
	{
		var nPos = null;
		if (this.UseArray)
		{
			for (var nIndex = 0, nCount = this.PosArray.length; nIndex < nCount; ++nIndex)
			{
				if (null === nPos || nPos > this.PosArray[nIndex])
					nPos = this.PosArray[nIndex];
			}

			if (null === nPos)
				nPos = 0;
		}
		else
		{
			nPos = this.Pos;
		}

		return nPos;
	};
	window['AscDFH'].CChangesBaseContentChange = CChangesBaseContentChange;
	/**
	 * Базовый класс для изменения свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBase}
	 */
	function CChangesBaseProperty(Class, Old, New, Color)
	{
		CChangesBase.call(this, Class);

		this.Color = true === Color ? true : false;
		this.Old   = Old;
		this.New   = New;
	}

	CChangesBaseProperty.prototype = Object.create(CChangesBase.prototype);
	CChangesBaseProperty.prototype.constructor = CChangesBaseProperty;
	CChangesBaseProperty.prototype.Undo = function()
	{
		this.private_SetValue(this.Old);
	};
	CChangesBaseProperty.prototype.Redo = function()
	{
		this.private_SetValue(this.New);
	};
	CChangesBaseProperty.prototype.private_SetValue = function(Value)
	{
		// Эту функцию нужно переопределить в дочернем классе
	};
	CChangesBaseProperty.prototype.CreateReverseChange = function()
	{
		return new this.constructor(this.Class, this.New, this.Old, this.Color);
	};
	CChangesBaseProperty.prototype.Merge = function(oChange)
	{
		if (oChange.Class === this.Class && oChange.Type === this.Type)
		{
			this.New = oChange.New;
			return false;
		}

		return true;
	};

	window['AscDFH'].CChangesBaseProperty = CChangesBaseProperty;
	/**
	 * Базовый класс для изменения булевых свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseBoolProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseBoolProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseBoolProperty.prototype.constructor = CChangesBaseBoolProperty;
	CChangesBaseBoolProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : New value
		// 4-bit : IsUndefined Old
		// 5-bit : Old value

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;
		else if (true === this.New)
			nFlags |= 4;

		if (undefined === this.Old)
			nFlags |= 8;
		else if (true === this.Old)
			nFlags |= 16;

		Writer.WriteLong(nFlags);
	};
	CChangesBaseBoolProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : New value
		// 4-bit : IsUndefined Old
		// 5-bit : Old value

		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
			this.New = undefined;
		else if (nFlags & 4)
			this.New = true;
		else
			this.New = false;

		if (nFlags & 8)
			this.Old = undefined;
		else if (nFlags & 16)
			this.Old = true;
		else
			this.Old = false;
	};
	window['AscDFH'].CChangesBaseBoolProperty = CChangesBaseBoolProperty;
	/**
	 * Базовый класс для изменения числовых (double) свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseDoubleProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseDoubleProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseDoubleProperty.prototype.constructor = CChangesBaseDoubleProperty;
	CChangesBaseDoubleProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// double : New
		// double : Old

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;

		if (undefined === this.Old)
			nFlags |= 4;

		Writer.WriteLong(nFlags);

		if (undefined !== this.New)
			Writer.WriteDouble(this.New);

		if (undefined !== this.Old)
			Writer.WriteDouble(this.Old);
	};
	CChangesBaseDoubleProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// double : New
		// double : Old


		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
			this.New = undefined;
		else
			this.New = Reader.GetDouble();

		if (nFlags & 4)
			this.Old = undefined;
		else
			this.Old = Reader.GetDouble();
	};
	window['AscDFH'].CChangesBaseDoubleProperty = CChangesBaseDoubleProperty;
	/**
	 * Базовый класс для изменения объектных свойств, т.е. если свойство задано объектом.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseObjectProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseObjectProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseObjectProperty.prototype.constructor = CChangesBaseObjectProperty;
	CChangesBaseObjectProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// Variable : New
		// Variable : Old

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;

		if (undefined === this.Old)
			nFlags |= 4;

		Writer.WriteLong(nFlags);

		if (undefined !== this.New && this.New.Write_ToBinary)
			this.New.Write_ToBinary(Writer);

		if (undefined !== this.Old && this.Old.Write_ToBinary)
			this.Old.Write_ToBinary(Writer);
	};
	CChangesBaseObjectProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// Variable : New
		// Variable : Old

		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
		{
			if (true === this.private_IsCreateEmptyObject())
				this.New = this.private_CreateObject();
			else
				this.New = undefined;
		}
		else
		{
			this.New = this.private_CreateObject();
			if (this.New && this.New.Read_FromBinary)
				this.New.Read_FromBinary(Reader);
		}

		if (nFlags & 4)
		{
			if (true === this.private_IsCreateEmptyObject())
				this.Old = this.private_CreateObject();
			else
				this.Old = undefined;
		}
		else
		{
			this.Old = this.private_CreateObject();
			if (this.Old && this.Old.Read_FromBinary)
				this.Old.Read_FromBinary(Reader);
		}
	};
	CChangesBaseObjectProperty.prototype.private_CreateObject = function()
	{
		// Эту функцию нужно переопределить в дочернем классе
		return null;
	};
	CChangesBaseObjectProperty.prototype.private_IsCreateEmptyObject = function()
	{
		return false;
	};
	window['AscDFH'].CChangesBaseObjectProperty = CChangesBaseObjectProperty;
	/**
	 * Базовый класс для изменения числовых (long) свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseLongProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseLongProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseLongProperty.prototype.constructor = CChangesBaseLongProperty;
	CChangesBaseLongProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// long : New
		// long : Old

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;

		if (undefined === this.Old)
			nFlags |= 4;

		Writer.WriteLong(nFlags);

		if (undefined !== this.New)
			Writer.WriteLong(this.New);

		if (undefined !== this.Old)
			Writer.WriteLong(this.Old);
	};
	CChangesBaseLongProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// long : New
		// long : Old


		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
			this.New = undefined;
		else
			this.New = Reader.GetLong();

		if (nFlags & 4)
			this.Old = undefined;
		else
			this.Old = Reader.GetLong();
	};
	window['AscDFH'].CChangesBaseLongProperty = CChangesBaseLongProperty;
	/**
	 * Базовый класс для изменения строковых свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseStringProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseStringProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseStringProperty.prototype.constructor = CChangesBaseStringProperty;
	CChangesBaseStringProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// string : New
		// string : Old

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;

		if (undefined === this.Old)
			nFlags |= 4;

		Writer.WriteLong(nFlags);

		if (undefined !== this.New)
			Writer.WriteString2(this.New);

		if (undefined !== this.Old)
			Writer.WriteString2(this.Old);
	};
	CChangesBaseStringProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// string : New
		// string : Old


		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
			this.New = undefined;
		else
			this.New = Reader.GetString2();

		if (nFlags & 4)
			this.Old = undefined;
		else
			this.Old = Reader.GetString2();
	};
	window['AscDFH'].CChangesBaseStringProperty = CChangesBaseStringProperty;
	/**
	 * Базовый класс для изменения числовых (byte) свойств.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseByteProperty(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseByteProperty.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseByteProperty.prototype.constructor = CChangesBaseByteProperty;
	CChangesBaseByteProperty.prototype.WriteToBinary = function(Writer)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// byte  : New
		// byte  : Old

		var nFlags = 0;

		if (false !== this.Color)
			nFlags |= 1;

		if (undefined === this.New)
			nFlags |= 2;

		if (undefined === this.Old)
			nFlags |= 4;

		Writer.WriteLong(nFlags);

		if (undefined !== this.New)
			Writer.WriteByte(this.New);

		if (undefined !== this.Old)
			Writer.WriteByte(this.Old);
	};
	CChangesBaseByteProperty.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : Flag
		// 1-bit : Подсвечивать ли данные изменения
		// 2-bit : IsUndefined New
		// 3-bit : IsUndefined Old
		// byte  : New
		// byte  : Old


		var nFlags = Reader.GetLong();

		if (nFlags & 1)
			this.Color = true;
		else
			this.Color = false;

		if (nFlags & 2)
			this.New = undefined;
		else
			this.New = Reader.GetByte();

		if (nFlags & 4)
			this.Old = undefined;
		else
			this.Old = Reader.GetByte();
	};
	window['AscDFH'].CChangesBaseByteProperty = CChangesBaseByteProperty;
	/**
	 * Базовый класс для изменения числовых(long) значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseLongValue(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseLongValue.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseLongValue.prototype.constructor = CChangesBaseLongValue;
	CChangesBaseLongValue.prototype.WriteToBinary = function(Writer)
	{
		// Long  : New
		// Long  : Old

		Writer.WriteLong(this.New);
		Writer.WriteLong(this.Old);
	};
	CChangesBaseLongValue.prototype.ReadFromBinary = function(Reader)
	{
		// Long  : New
		// Long  : Old

		this.New = Reader.GetLong();
		this.Old = Reader.GetLong();
	};
	window['AscDFH'].CChangesBaseLongValue = CChangesBaseLongValue;
	/**
	 * Базовый класс для изменения булевых значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseBoolValue(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseBoolValue.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseBoolValue.prototype.constructor = CChangesBaseBoolValue;
	CChangesBaseBoolValue.prototype.WriteToBinary = function(Writer)
	{
		// Bool  : New
		// Bool  : Old

		Writer.WriteBool(this.New);
		Writer.WriteBool(this.Old);
	};
	CChangesBaseBoolValue.prototype.ReadFromBinary = function(Reader)
	{
		// Bool  : New
		// Bool  : Old

		this.New = Reader.GetBool();
		this.Old = Reader.GetBool();
	};
	window['AscDFH'].CChangesBaseBoolValue = CChangesBaseBoolValue;
	/**
	 * Базовый класс для изменения объектных значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseObjectProperty}
	 */
	function CChangesBaseObjectValue(Class, Old, New, Color)
	{
		CChangesBaseObjectProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseObjectValue.prototype = Object.create(CChangesBaseObjectProperty.prototype);
	CChangesBaseObjectValue.prototype.constructor = CChangesBaseObjectValue;
	CChangesBaseObjectValue.prototype.private_IsCreateEmptyObject = function()
	{
		return true;
	};
	window['AscDFH'].CChangesBaseObjectValue = CChangesBaseObjectValue;
	/**
	 * Базовый класс для изменения строковых значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseStringValue(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseStringValue.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseStringValue.prototype.constructor = CChangesBaseStringValue;
	CChangesBaseStringValue.prototype.WriteToBinary = function(Writer)
	{
		// String : New
		// String : Old

		Writer.WriteString2(this.New);
		Writer.WriteString2(this.Old);
	};
	CChangesBaseStringValue.prototype.ReadFromBinary = function(Reader)
	{
		// String : New
		// String : Old

		this.New = Reader.GetString2();
		this.Old = Reader.GetString2();
	};
	window['AscDFH'].CChangesBaseStringValue = CChangesBaseStringValue;
	/**
	 * Базовый класс для изменения числовых(byte) значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseByteValue(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseByteValue.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseByteValue.prototype.constructor = CChangesBaseByteValue;
	CChangesBaseByteValue.prototype.WriteToBinary = function(Writer)
	{
		// Byte  : New
		// Byte  : Old

		Writer.WriteByte(this.New);
		Writer.WriteByte(this.Old);
	};
	CChangesBaseByteValue.prototype.ReadFromBinary = function(Reader)
	{
		// Byte  : New
		// Byte  : Old

		this.New = Reader.GetByte();
		this.Old = Reader.GetByte();
	};
	window['AscDFH'].CChangesBaseByteValue = CChangesBaseByteValue;
	/**
	 * Базовый класс для изменения числовых(double) значений.
	 * @constructor
	 * @extends {AscDFH.CChangesBaseProperty}
	 */
	function CChangesBaseDoubleValue(Class, Old, New, Color)
	{
		CChangesBaseProperty.call(this, Class, Old, New, Color);
	}

	CChangesBaseDoubleValue.prototype = Object.create(CChangesBaseProperty.prototype);
	CChangesBaseDoubleValue.prototype.constructor = CChangesBaseDoubleValue;
	CChangesBaseDoubleValue.prototype.WriteToBinary = function(Writer)
	{
		// Double : New
		// Double : Old

		Writer.WriteDouble(this.New);
		Writer.WriteDouble(this.Old);
	};
	CChangesBaseDoubleValue.prototype.ReadFromBinary = function(Reader)
	{
		// Double : New
		// Double : Old

		this.New = Reader.GetDouble();
		this.Old = Reader.GetDouble();
	};
	window['AscDFH'].CChangesBaseDoubleValue = CChangesBaseDoubleValue;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

/**
 * User: Ilja.Kirillov
 * Date: 26.10.2016
 * Time: 18:45
 */

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function(window, undefined)
{
	function CTableId()
	{
		this.m_aPairs        = null;
		this.m_bTurnOff      = false;
		this.m_oFactoryClass = {};
		this.Id              = null;
		this.isInit          = false;
	}

	CTableId.prototype.checkInit = function()
	{
		return this.isInit;
	};
	CTableId.prototype.init = function()
	{
		this.m_aPairs        = {};
		this.m_bTurnOff      = false;
		this.m_oFactoryClass = {};
		this.Id              = AscCommon.g_oIdCounter.Get_NewId();
		this.Add(this, this.Id);
		this.private_InitFactoryClass();
		this.isInit = true;
	};
	CTableId.prototype.Add = function(Class, Id)
	{
		if (false === this.m_bTurnOff)
		{
			Class.Id          = Id;
			this.m_aPairs[Id] = Class;

			AscCommon.History.Add(new AscCommon.CChangesTableIdAdd(this, Id, Class));
		}
	};
	CTableId.prototype.TurnOff = function()
	{
		this.m_bTurnOff = true;
	};
	CTableId.prototype.TurnOn = function()
	{
		this.m_bTurnOff = false;
	};
	/**
	 * Получаем указатель на класс по Id
	 * @param Id
	 * @returns {*}
	 */
	CTableId.prototype.Get_ById = function(Id)
	{
		if ("" === Id)
			return null;

		if (this.m_aPairs[Id])
			return this.m_aPairs[Id];

		return null;
	};
	/**
	 * Получаем Id, по классу (вообще, данную функцию лучше не использовать)
	 * @param Class
	 * @returns {*}
	 */
	CTableId.prototype.Get_ByClass = function(Class)
	{
		if (Class.Get_Id)
			return Class.Get_Id();

		if (Class.GetId())
			return Class.GetId();

		return null;
	};
	CTableId.prototype.Get_Id = function()
	{
		return this.Id;
	};
	CTableId.prototype.Clear = function()
	{
		this.m_aPairs   = {};
		this.m_bTurnOff = false;
		this.Id         = AscCommon.g_oIdCounter.Get_NewId();
		this.Add(this, this.Id);
	};
	CTableId.prototype.private_InitFactoryClass = function()
	{
		this.m_oFactoryClass[AscDFH.historyitem_type_Paragraph]              = AscCommonWord.Paragraph;
		this.m_oFactoryClass[AscDFH.historyitem_type_TextPr]                 = AscCommonWord.ParaTextPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_Hyperlink]              = AscCommonWord.ParaHyperlink;
		this.m_oFactoryClass[AscDFH.historyitem_type_Drawing]                = AscCommonWord.ParaDrawing;
		this.m_oFactoryClass[AscDFH.historyitem_type_Table]                  = AscCommonWord.CTable;
		this.m_oFactoryClass[AscDFH.historyitem_type_TableRow]               = AscCommonWord.CTableRow;
		this.m_oFactoryClass[AscDFH.historyitem_type_TableCell]              = AscCommonWord.CTableCell;
		this.m_oFactoryClass[AscDFH.historyitem_type_DocumentContent]        = AscCommonWord.CDocumentContent;
		this.m_oFactoryClass[AscDFH.historyitem_type_HdrFtr]                 = AscCommonWord.CHeaderFooter;
		this.m_oFactoryClass[AscDFH.historyitem_type_AbstractNum]            = AscCommonWord.CAbstractNum;
		this.m_oFactoryClass[AscDFH.historyitem_type_Comment]                = AscCommon.CComment;
		this.m_oFactoryClass[AscDFH.historyitem_type_Style]                  = AscCommonWord.CStyle;
		this.m_oFactoryClass[AscDFH.historyitem_type_CommentMark]            = AscCommon.ParaComment;
		this.m_oFactoryClass[AscDFH.historyitem_type_ParaRun]                = AscCommonWord.ParaRun;
		this.m_oFactoryClass[AscDFH.historyitem_type_Section]                = AscCommonWord.CSectionPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_Field]                  = AscCommonWord.ParaField;
		this.m_oFactoryClass[AscDFH.historyitem_type_FootEndNote]            = AscCommonWord.CFootEndnote;
		this.m_oFactoryClass[AscDFH.historyitem_type_DefaultShapeDefinition] = AscFormat.DefaultShapeDefinition;
		this.m_oFactoryClass[AscDFH.historyitem_type_CNvPr]                  = AscFormat.CNvPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_NvPr]                   = AscFormat.NvPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_Ph]                     = AscFormat.Ph;
		this.m_oFactoryClass[AscDFH.historyitem_type_UniNvPr]                = AscFormat.UniNvPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_StyleRef]               = AscFormat.StyleRef;
		this.m_oFactoryClass[AscDFH.historyitem_type_FontRef]                = AscFormat.FontRef;
		this.m_oFactoryClass[AscDFH.historyitem_type_Chart]                  = AscFormat.CChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_ChartSpace]             = AscFormat.CChartSpace;
		this.m_oFactoryClass[AscDFH.historyitem_type_Legend]                 = AscFormat.CLegend;
		this.m_oFactoryClass[AscDFH.historyitem_type_Layout]                 = AscFormat.CLayout;
		this.m_oFactoryClass[AscDFH.historyitem_type_LegendEntry]            = AscFormat.CLegendEntry;
		this.m_oFactoryClass[AscDFH.historyitem_type_PivotFmt]               = AscFormat.CPivotFmt;
		this.m_oFactoryClass[AscDFH.historyitem_type_DLbl]                   = AscFormat.CDLbl;
		this.m_oFactoryClass[AscDFH.historyitem_type_Marker]                 = AscFormat.CMarker;
		this.m_oFactoryClass[AscDFH.historyitem_type_PlotArea]               = AscFormat.CPlotArea;
		this.m_oFactoryClass[AscDFH.historyitem_type_NumFmt]                 = AscFormat.CNumFmt;
		this.m_oFactoryClass[AscDFH.historyitem_type_Scaling]                = AscFormat.CScaling;
		this.m_oFactoryClass[AscDFH.historyitem_type_DTable]                 = AscFormat.CDTable;
		this.m_oFactoryClass[AscDFH.historyitem_type_LineChart]              = AscFormat.CLineChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_DLbls]                  = AscFormat.CDLbls;
		this.m_oFactoryClass[AscDFH.historyitem_type_UpDownBars]             = AscFormat.CUpDownBars;
		this.m_oFactoryClass[AscDFH.historyitem_type_BarChart]               = AscFormat.CBarChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_BubbleChart]            = AscFormat.CBubbleChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_DoughnutChart]          = AscFormat.CDoughnutChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_OfPieChart]             = AscFormat.COfPieChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_PieChart]               = AscFormat.CPieChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_RadarChart]             = AscFormat.CRadarChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_ScatterChart]           = AscFormat.CScatterChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_StockChart]             = AscFormat.CStockChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_SurfaceChart]           = AscFormat.CSurfaceChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_BandFmt]                = AscFormat.CBandFmt;
		this.m_oFactoryClass[AscDFH.historyitem_type_AreaChart]              = AscFormat.CAreaChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_ScatterSer]             = AscFormat.CScatterSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_DPt]                    = AscFormat.CDPt;
		this.m_oFactoryClass[AscDFH.historyitem_type_ErrBars]                = AscFormat.CErrBars;
		this.m_oFactoryClass[AscDFH.historyitem_type_MinusPlus]              = AscFormat.CMinusPlus;
		this.m_oFactoryClass[AscDFH.historyitem_type_NumLit]                 = AscFormat.CNumLit;
		this.m_oFactoryClass[AscDFH.historyitem_type_NumericPoint]           = AscFormat.CNumericPoint;
		this.m_oFactoryClass[AscDFH.historyitem_type_NumRef]                 = AscFormat.CNumRef;
		this.m_oFactoryClass[AscDFH.historyitem_type_TrendLine]              = AscFormat.CTrendLine;
		this.m_oFactoryClass[AscDFH.historyitem_type_Tx]                     = AscFormat.CTx;
		this.m_oFactoryClass[AscDFH.historyitem_type_StrRef]                 = AscFormat.CStrRef;
		this.m_oFactoryClass[AscDFH.historyitem_type_StrCache]               = AscFormat.CStrCache;
		this.m_oFactoryClass[AscDFH.historyitem_type_StrPoint]               = AscFormat.CStringPoint;
		this.m_oFactoryClass[AscDFH.historyitem_type_XVal]                   = AscFormat.CXVal;
		this.m_oFactoryClass[AscDFH.historyitem_type_MultiLvlStrRef]         = AscFormat.CMultiLvlStrRef;
		this.m_oFactoryClass[AscDFH.historyitem_type_MultiLvlStrCache]       = AscFormat.CMultiLvlStrCache;
		this.m_oFactoryClass[AscDFH.historyitem_type_StringLiteral]          = AscFormat.CStringLiteral;
		this.m_oFactoryClass[AscDFH.historyitem_type_YVal]                   = AscFormat.CYVal;
		this.m_oFactoryClass[AscDFH.historyitem_type_AreaSeries]             = AscFormat.CAreaSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_Cat]                    = AscFormat.CCat;
		this.m_oFactoryClass[AscDFH.historyitem_type_PictureOptions]         = AscFormat.CPictureOptions;
		this.m_oFactoryClass[AscDFH.historyitem_type_RadarSeries]            = AscFormat.CRadarSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_BarSeries]              = AscFormat.CBarSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_LineSeries]             = AscFormat.CLineSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_PieSeries]              = AscFormat.CPieSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_SurfaceSeries]          = AscFormat.CSurfaceSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_BubbleSeries]           = AscFormat.CBubbleSeries;
		this.m_oFactoryClass[AscDFH.historyitem_type_ExternalData]           = AscFormat.CExternalData;
		this.m_oFactoryClass[AscDFH.historyitem_type_PivotSource]            = AscFormat.CPivotSource;
		this.m_oFactoryClass[AscDFH.historyitem_type_Protection]             = AscFormat.CProtection;
		this.m_oFactoryClass[AscDFH.historyitem_type_ChartWall]              = AscFormat.CChartWall;
		this.m_oFactoryClass[AscDFH.historyitem_type_View3d]                 = AscFormat.CView3d;
		this.m_oFactoryClass[AscDFH.historyitem_type_ChartText]              = AscFormat.CChartText;
		this.m_oFactoryClass[AscDFH.historyitem_type_ShapeStyle]             = AscFormat.CShapeStyle;
		this.m_oFactoryClass[AscDFH.historyitem_type_Xfrm]                   = AscFormat.CXfrm;
		this.m_oFactoryClass[AscDFH.historyitem_type_SpPr]                   = AscFormat.CSpPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_ClrScheme]              = AscFormat.ClrScheme;
		this.m_oFactoryClass[AscDFH.historyitem_type_ClrMap]                 = AscFormat.ClrMap;
		this.m_oFactoryClass[AscDFH.historyitem_type_ExtraClrScheme]         = AscFormat.ExtraClrScheme;
		this.m_oFactoryClass[AscDFH.historyitem_type_FontCollection]         = AscFormat.FontCollection;
		this.m_oFactoryClass[AscDFH.historyitem_type_FontScheme]             = AscFormat.FontScheme;
		this.m_oFactoryClass[AscDFH.historyitem_type_FormatScheme]           = AscFormat.FmtScheme;
		this.m_oFactoryClass[AscDFH.historyitem_type_ThemeElements]          = AscFormat.ThemeElements;
		this.m_oFactoryClass[AscDFH.historyitem_type_HF]                     = AscFormat.HF;
		this.m_oFactoryClass[AscDFH.historyitem_type_BgPr]                   = AscFormat.CBgPr;
		this.m_oFactoryClass[AscDFH.historyitem_type_Bg]                     = AscFormat.CBg;
		this.m_oFactoryClass[AscDFH.historyitem_type_PrintSettings]          = AscFormat.CPrintSettings;
		this.m_oFactoryClass[AscDFH.historyitem_type_HeaderFooterChart]      = AscFormat.CHeaderFooterChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_PageMarginsChart]       = AscFormat.CPageMarginsChart;
		this.m_oFactoryClass[AscDFH.historyitem_type_PageSetup]              = AscFormat.CPageSetup;
		this.m_oFactoryClass[AscDFH.historyitem_type_Shape]                  = AscFormat.CShape;
		this.m_oFactoryClass[AscDFH.historyitem_type_DispUnits]              = AscFormat.CDispUnits;
		this.m_oFactoryClass[AscDFH.historyitem_type_GroupShape]             = AscFormat.CGroupShape;
		this.m_oFactoryClass[AscDFH.historyitem_type_ImageShape]             = AscFormat.CImageShape;
		this.m_oFactoryClass[AscDFH.historyitem_type_Geometry]               = AscFormat.Geometry;
		this.m_oFactoryClass[AscDFH.historyitem_type_Path]                   = AscFormat.Path;
		this.m_oFactoryClass[AscDFH.historyitem_type_TextBody]               = AscFormat.CTextBody;
		this.m_oFactoryClass[AscDFH.historyitem_type_CatAx]                  = AscFormat.CCatAx;
		this.m_oFactoryClass[AscDFH.historyitem_type_ValAx]                  = AscFormat.CValAx;
		this.m_oFactoryClass[AscDFH.historyitem_type_WrapPolygon]            = AscCommonWord.CWrapPolygon;
		this.m_oFactoryClass[AscDFH.historyitem_type_DateAx]                 = AscFormat.CDateAx;
		this.m_oFactoryClass[AscDFH.historyitem_type_SerAx]                  = AscFormat.CSerAx;
		this.m_oFactoryClass[AscDFH.historyitem_type_Title]                  = AscFormat.CTitle;
		this.m_oFactoryClass[AscDFH.historyitem_type_OleObject]              = AscFormat.COleObject;
        this.m_oFactoryClass[AscDFH.historyitem_type_Cnx]                    = AscFormat.CConnectionShape;
		this.m_oFactoryClass[AscDFH.historyitem_type_DrawingContent]         = AscFormat.CDrawingDocContent;
		this.m_oFactoryClass[AscDFH.historyitem_type_Math]                   = AscCommonWord.ParaMath;
		this.m_oFactoryClass[AscDFH.historyitem_type_MathContent]            = AscCommonWord.CMathContent;
		this.m_oFactoryClass[AscDFH.historyitem_type_acc]                    = AscCommonWord.CAccent;
		this.m_oFactoryClass[AscDFH.historyitem_type_bar]                    = AscCommonWord.CBar;
		this.m_oFactoryClass[AscDFH.historyitem_type_box]                    = AscCommonWord.CBox;
		this.m_oFactoryClass[AscDFH.historyitem_type_borderBox]              = AscCommonWord.CBorderBox;
		this.m_oFactoryClass[AscDFH.historyitem_type_delimiter]              = AscCommonWord.CDelimiter;
		this.m_oFactoryClass[AscDFH.historyitem_type_eqArr]                  = AscCommonWord.CEqArray;
		this.m_oFactoryClass[AscDFH.historyitem_type_frac]                   = AscCommonWord.CFraction;
		this.m_oFactoryClass[AscDFH.historyitem_type_mathFunc]               = AscCommonWord.CMathFunc;
		this.m_oFactoryClass[AscDFH.historyitem_type_groupChr]               = AscCommonWord.CGroupCharacter;
		this.m_oFactoryClass[AscDFH.historyitem_type_lim]                    = AscCommonWord.CLimit;
		this.m_oFactoryClass[AscDFH.historyitem_type_matrix]                 = AscCommonWord.CMathMatrix;
		this.m_oFactoryClass[AscDFH.historyitem_type_nary]                   = AscCommonWord.CNary;
		this.m_oFactoryClass[AscDFH.historyitem_type_phant]                  = AscCommonWord.CPhantom;
		this.m_oFactoryClass[AscDFH.historyitem_type_rad]                    = AscCommonWord.CRadical;
		this.m_oFactoryClass[AscDFH.historyitem_type_deg_subsup]             = AscCommonWord.CDegreeSubSup;
		this.m_oFactoryClass[AscDFH.historyitem_type_deg]                    = AscCommonWord.CDegree;
		this.m_oFactoryClass[AscDFH.historyitem_type_BlockLevelSdt]          = AscCommonWord.CBlockLevelSdt;
		this.m_oFactoryClass[AscDFH.historyitem_type_InlineLevelSdt]         = AscCommonWord.CInlineLevelSdt;
		this.m_oFactoryClass[AscDFH.historyitem_type_ParaBookmark]           = AscCommonWord.CParagraphBookmark;
		this.m_oFactoryClass[AscDFH.historyitem_type_Num]                    = AscCommonWord.CNum;


		if (window['AscCommonSlide'])
		{
			this.m_oFactoryClass[AscDFH.historyitem_type_Slide]               = AscCommonSlide.Slide;
			this.m_oFactoryClass[AscDFH.historyitem_type_SlideLayout]         = AscCommonSlide.SlideLayout;
			this.m_oFactoryClass[AscDFH.historyitem_type_SlideMaster]         = AscCommonSlide.MasterSlide;
			this.m_oFactoryClass[AscDFH.historyitem_type_SlideComments]       = AscCommonSlide.SlideComments;
			this.m_oFactoryClass[AscDFH.historyitem_type_PropLocker]          = AscCommonSlide.PropLocker;
			this.m_oFactoryClass[AscDFH.historyitem_type_NotesMaster]         = AscCommonSlide.CNotesMaster;
			this.m_oFactoryClass[AscDFH.historyitem_type_Notes]               = AscCommonSlide.CNotes;
			this.m_oFactoryClass[AscDFH.historyitem_type_PresentationSection] = AscCommonSlide.CPrSection;
		}

		this.m_oFactoryClass[AscDFH.historyitem_type_Theme]                  = AscFormat.CTheme;
		this.m_oFactoryClass[AscDFH.historyitem_type_GraphicFrame]           = AscFormat.CGraphicFrame;

		if (window['AscCommonExcel'])
		{
			this.m_oFactoryClass[AscDFH.historyitem_type_Sparkline] = AscCommonExcel.sparklineGroup;
			this.m_oFactoryClass[AscDFH.historyitem_type_PivotTableDefinition] = Asc.CT_pivotTableDefinition;
		}

		this.m_oFactoryClass[AscDFH.historyitem_type_DocumentMacros] = AscCommon.CDocumentMacros;
	};
	CTableId.prototype.GetClassFromFactory = function(nType)
	{
		if (this.m_oFactoryClass[nType])
			return new this.m_oFactoryClass[nType]();

		return null;
	};
	CTableId.prototype.Refresh_RecalcData = function(Data)
	{
	};
	//-----------------------------------------------------------------------------------
	// Функции для работы с совместным редактирования
	//-----------------------------------------------------------------------------------
	CTableId.prototype.Unlock = function(Data)
	{
		// Ничего не делаем
	};

	window["AscCommon"].g_oTableId = new CTableId();
	window["AscCommon"].CTableId = CTableId;
})(window);
/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

/**
 * User: Ilja.Kirillov
 * Date: 26.10.2016
 * Time: 18:53
 */

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
	function(window, undefined)
{
	/**
	 * @constructor
	 * @extends {AscDFH.CChangesBase}
	 */
	function CChangesTableIdAdd(Class, Id, NewClass)
	{
		AscDFH.CChangesBase.call(this, Class);

		this.Id       = Id;
		this.NewClass = NewClass;
	}

	CChangesTableIdAdd.prototype = Object.create(AscDFH.CChangesBase.prototype);
	CChangesTableIdAdd.prototype.constructor = CChangesTableIdAdd;
	CChangesTableIdAdd.prototype.Type = AscDFH.historyitem_TableId_Add;
	CChangesTableIdAdd.prototype.Undo = function()
	{
	};
	CChangesTableIdAdd.prototype.Redo = function()
	{
	};
	CChangesTableIdAdd.prototype.WriteToBinary = function(Writer)
	{
		// String   : Id элемента
		// Varibale : сам элемент

		Writer.WriteString2(this.Id);
		this.NewClass.Write_ToBinary2(Writer);
	};
	CChangesTableIdAdd.prototype.ReadFromBinary = function(Reader)
	{
		// String   : Id элемента
		// Varibale : сам элемент

		this.Id       = Reader.GetString2();
		this.NewClass = this.private_ReadClassFromBinary(Reader);
	};
	CChangesTableIdAdd.prototype.Load = function(Color)
	{
		this.Class.m_aPairs[this.Id] = this.NewClass;
	};
	CChangesTableIdAdd.prototype.RefreshRecalcData = function()
	{
	};
	CChangesTableIdAdd.prototype.private_ReadClassFromBinary = function(Reader)
	{
		var oTableId = this.Class;

		var ElementType = Reader.GetLong();

		oTableId.TurnOff();
		var Element = oTableId.GetClassFromFactory(ElementType);

		if (null !== Element)
			Element.Read_FromBinary2(Reader);

		oTableId.TurnOn();

		return Element;
	};
	CChangesTableIdAdd.prototype.CreateReverseChange = function()
	{
		return null;
	};
	window["AscCommon"].CChangesTableIdAdd = CChangesTableIdAdd;
	/**
	 * @constructor
	 * @extends {AscDFH.CChangesBase}
	 */
	function CChangesTableIdDescription(Class, FileCheckSum, FileSize, Description, ItemsCount, PointIndex, StartPoint, LastPoint, SumIndex, DeletedIndex)
	{
		AscDFH.CChangesBase.call(this, Class);

		this.FileCheckSum  = FileCheckSum;
		this.FileSize      = FileSize;
		this.Description   = Description;
		this.ItemsCount    = ItemsCount;
		this.PointIndex    = PointIndex;
		this.StartPoint    = StartPoint;
		this.LastPoint     = LastPoint;
		this.SumIndex      = SumIndex;
		this.DeletedIndex  = DeletedIndex;
		this.VersionString = "0.0.0.0.@@Rev";
	}

	CChangesTableIdDescription.prototype = Object.create(AscDFH.CChangesBase.prototype);
	CChangesTableIdDescription.prototype.constructor = CChangesTableIdDescription;
	CChangesTableIdDescription.prototype.Type = AscDFH.historyitem_TableId_Description;
	CChangesTableIdDescription.prototype.Undo = function()
	{
	};
	CChangesTableIdDescription.prototype.Redo = function()
	{
	};
	CChangesTableIdDescription.prototype.WriteToBinary = function(Writer)
	{
		// Long : FileCheckSum
		// Long : FileSize
		// Long : Description
		// Long : ItemsCount
		// Long : PointIndex
		// Long : StartPoint
		// Long : LastPoint
		// Long : SumIndex
		// Long : DeletedIndex
		// String : Версия SDK

		Writer.WriteLong(this.FileCheckSum);
		Writer.WriteLong(this.FileSize);
		Writer.WriteLong(this.Description);
		Writer.WriteLong(this.ItemsCount);
		Writer.WriteLong(this.PointIndex);
		Writer.WriteLong(this.StartPoint);
		Writer.WriteLong(this.LastPoint);
		Writer.WriteLong(this.SumIndex);
		Writer.WriteLong(null === this.DeletedIndex ? -10 : this.DeletedIndex);
		Writer.WriteString2(this.VersionString);
	};
	CChangesTableIdDescription.prototype.ReadFromBinary = function(Reader)
	{
		// Long : FileCheckSum
		// Long : FileSize
		// Long : Description
		// Long : ItemsCount
		// Long : PointIndex
		// Long : StartPoint
		// Long : LastPoint
		// Long : SumIndex
		// Long : DeletedIndex
		// String : Версия SDK

		this.FileCheckSum  = Reader.GetLong();
		this.FileSize      = Reader.GetLong();
		this.Description   = Reader.GetLong();
		this.ItemsCount    = Reader.GetLong();
		this.PointIndex    = Reader.GetLong();
		this.StartPoint    = Reader.GetLong();
		this.LastPoint     = Reader.GetLong();
		this.SumIndex      = Reader.GetLong();
		this.DeletedIndex  = Reader.GetLong();
		this.VersionString = Reader.GetString2();
	};
	CChangesTableIdDescription.prototype.Load = function(Color)
	{
		// var CollaborativeEditing = AscCommon.CollaborativeEditing;
		// // CollaborativeEditing LOG
		// console.log("ItemsCount2  " + CollaborativeEditing.m_nErrorLog_PointChangesCount);
		// if (CollaborativeEditing.m_nErrorLog_PointChangesCount !== CollaborativeEditing.m_nErrorLog_SavedPCC)
		// 	console.log("========================= BAD Changes Count in Point =============================");
		// if (CollaborativeEditing.m_nErrorLog_CurPointIndex + 1 !== this.PointIndex && 0 !== this.PointIndex)
		// 	console.log("========================= BAD Point index ========================================");
		// var bBadSumIndex = false;
		// if (0 === this.PointIndex)
		// {
		// 	CollaborativeEditing.m_nErrorLog_SumIndex = 0;
		// }
		// else
		// {
		// 	// Потому что мы не учитываем данное изменение
		// 	CollaborativeEditing.m_nErrorLog_SumIndex += CollaborativeEditing.m_nErrorLog_SavedPCC + 1;
		// 	if (this.PointIndex === this.StartPoint)
		// 	{
		// 		if (CollaborativeEditing.m_nErrorLog_SumIndex !== this.SumIndex)
		// 			bBadSumIndex = true;
		//
		// 		console.log("SumIndex2    " + CollaborativeEditing.m_nErrorLog_SumIndex);
		// 		CollaborativeEditing.m_nErrorLog_SumIndex = this.SumIndex;
		// 	}
		// }
		//
		// console.log("----------------------------");
		// console.log("FileCheckSum " + this.FileCheckSum);
		// console.log("FileSize     " + this.FileSize);
		// console.log("Description  " + this.Description + " " +
		// 	AscDFH.GetHistoryPointStringDescription(this.Description));
		// console.log("PointIndex   " + this.PointIndex);
		// console.log("StartPoint   " + this.StartPoint);
		// console.log("LastPoint    " + this.LastPoint);
		// console.log("ItemsCount   " + this.ItemsCount);
		// console.log("SumIndex     " + this.SumIndex);
		// console.log("DeletedIndex " + (-10 === this.DeletedIndex ? null : this.DeletedIndex));
		// // -1 Чтобы не учитывалось данное изменение
		// CollaborativeEditing.m_nErrorLog_SavedPCC          = this.ItemsCount;
		// CollaborativeEditing.m_nErrorLog_PointChangesCount = -1;
		// CollaborativeEditing.m_nErrorLog_CurPointIndex     = this.PointIndex;
		// if (bBadSumIndex)
		// 	console.log("========================= BAD Sum index ==========================================");
	};
	CChangesTableIdDescription.prototype.RefreshRecalcData = function()
	{
	};
	CChangesTableIdDescription.prototype.CreateReverseChange = function()
	{
		return null;
	};
	window["AscCommon"].CChangesTableIdDescription = CChangesTableIdDescription;
	/**
	 * @constructor
	 * @extends {AscDFH.CChangesBase}
	 */
	function CChangesCommonAddWaterMark(Class, Url)
	{
		AscDFH.CChangesBase.call(this, Class);

		this.Url = Url ? Url : "";
	}

	CChangesCommonAddWaterMark.prototype = Object.create(AscDFH.CChangesBase.prototype);
	CChangesCommonAddWaterMark.prototype.constructor = CChangesCommonAddWaterMark;
	CChangesCommonAddWaterMark.prototype.Type = AscDFH.historyitem_Common_AddWatermark;
	CChangesCommonAddWaterMark.prototype.Undo = function()
	{
	};
	CChangesCommonAddWaterMark.prototype.Redo = function()
	{
	};
	CChangesCommonAddWaterMark.prototype.WriteToBinary = function(Writer)
	{
		Writer.WriteString2(this.Url);
	};
	CChangesCommonAddWaterMark.prototype.ReadFromBinary = function(Reader)
	{
		this.Url = Reader.GetString2();
	};
	CChangesCommonAddWaterMark.prototype.Load = function(Color)
	{
		var sUrl = this.Url;
		if (editor && editor.WordControl && editor.WordControl.m_oLogicDocument)
		{
			var oLogicDocument = editor.WordControl.m_oLogicDocument;
			if (oLogicDocument instanceof AscCommonWord.CDocument)
			{
				var oParaDrawing    = oLogicDocument.DrawingObjects.getTrialImage(sUrl);
				var oFirstParagraph = oLogicDocument.Get_FirstParagraph();
				AscFormat.ExecuteNoHistory(function()
				{
					var oRun = new AscCommonWord.ParaRun();
					oRun.Content.splice(0, 0, oParaDrawing);
					oFirstParagraph.Content.splice(0, 0, oRun);
					oLogicDocument.DrawingObjects.addGraphicObject(oParaDrawing);
				}, this, []);
			}
			else if (oLogicDocument instanceof AscCommonSlide.CPresentation)
			{
				if (oLogicDocument.Slides[0])
				{
					var oDrawing            = oLogicDocument.Slides[0].graphicObjects.createWatermarkImage(sUrl);
					oDrawing.spPr.xfrm.offX = (oLogicDocument.Width - oDrawing.spPr.xfrm.extX) / 2;
					oDrawing.spPr.xfrm.offY = (oLogicDocument.Height - oDrawing.spPr.xfrm.extY) / 2;
					oDrawing.parent         = oLogicDocument.Slides[0];
					oLogicDocument.Slides[0].cSld.spTree.push(oDrawing);
				}
			}
		}
		else
		{
			var oWsModel = window["Asc"]["editor"].wbModel.aWorksheets[0];
			if (oWsModel)
			{
				var objectRender          = new AscFormat.DrawingObjects();
				var oNewDrawing           = objectRender.createDrawingObject(AscCommon.c_oAscCellAnchorType.cellanchorAbsolute);
				var oImage                = AscFormat.DrawingObjectsController.prototype.createWatermarkImage(sUrl);
				oNewDrawing.ext.cx        = oImage.spPr.xfrm.extX;
				oNewDrawing.ext.cy        = oImage.spPr.xfrm.extY;
				oNewDrawing.graphicObject = oImage;
				oWsModel.Drawings.push(oNewDrawing);
			}
		}
	};
	CChangesCommonAddWaterMark.prototype.RefreshRecalcData = function()
	{
	};
	CChangesCommonAddWaterMark.prototype.CreateReverseChange = function()
	{
		return null;
	};
	window["AscCommon"].CChangesCommonAddWaterMark = CChangesCommonAddWaterMark;
})(window);



AscDFH.changesFactory[AscDFH.historyitem_TableId_Add]         = AscCommon.CChangesTableIdAdd;
AscDFH.changesFactory[AscDFH.historyitem_TableId_Description] = AscCommon.CChangesTableIdDescription;

AscDFH.changesFactory[AscDFH.historyitem_Common_AddWatermark] = AscCommon.CChangesCommonAddWaterMark;


//----------------------------------------------------------------------------------------------------------------------
// Карта зависимости изменений
//----------------------------------------------------------------------------------------------------------------------
AscDFH.changesRelationMap[AscDFH.historyitem_TableId_Add]         = [AscDFH.historyitem_TableId_Add];
AscDFH.changesRelationMap[AscDFH.historyitem_TableId_Reset]       = [AscDFH.historyitem_TableId_Reset];
AscDFH.changesRelationMap[AscDFH.historyitem_TableId_Description] = [AscDFH.historyitem_TableId_Description];
AscDFH.changesRelationMap[AscDFH.historyitem_Common_AddWatermark] = [AscDFH.historyitem_Common_AddWatermark];
//----------------------------------------------------------------------------------------------------------------------

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(
	/**
	 * @param {Window} window
	 * @param {undefined} undefined
	 */
	function ( window, undefined) {

		/** @constructor */
		function asc_CAdvancedOptions(id,opt){
			this.optionId = null;
			this.options = null;

			switch(id){
				case Asc.c_oAscAdvancedOptionsID.CSV:
					this.optionId = id;
					this.options = new asc_CCSVOptions(opt);
					break;
				case Asc.c_oAscAdvancedOptionsID.TXT:
					this.optionId = id;
					this.options = new asc_CTXTOptions(opt);
					break;
				case Asc.c_oAscAdvancedOptionsID.DRM:
					this.optionId = id;
					break;
			}
		}
		asc_CAdvancedOptions.prototype.asc_getOptionId = function(){ return this.optionId; };
		asc_CAdvancedOptions.prototype.asc_getOptions = function(){ return this.options; };

		/** @constructor */
		function asc_CCSVOptions(opt){
			this.codePages = function(){
				var arr = [], c, encodings = opt["encodings"];
				for(var i = 0; i < encodings.length; i++ ){
					c = new asc_CCodePage();
					c.init(encodings[i]);
					arr.push(c);
				}
				return arr;
			}();
			this.recommendedSettings = new asc_CCSVAdvancedOptions (opt["codepage"], opt["delimiter"]);
			this.data = opt["data"];
		}
		asc_CCSVOptions.prototype.asc_getCodePages = function(){ return this.codePages;};
		asc_CCSVOptions.prototype.asc_getRecommendedSettings = function () { return this.recommendedSettings; };
		asc_CCSVOptions.prototype.asc_getData = function () { return this.data; };

		/** @constructor */
		function asc_CTXTOptions(opt){
			this.codePages = function(){
				var arr = [], c, encodings = opt["encodings"];
				for(var i = 0; i < encodings.length; i++ ){
					c = new asc_CCodePage();
					c.init(encodings[i]);
					arr.push(c);
				}
				return arr;
			}();
			this.recommendedSettings = new asc_CTXTAdvancedOptions (opt["codepage"]);
			this.data = opt["data"];
		}
		asc_CTXTOptions.prototype.asc_getCodePages = function(){ return this.codePages;};
		asc_CTXTOptions.prototype.asc_getRecommendedSettings = function () { return this.recommendedSettings; };
		asc_CTXTOptions.prototype.asc_getData = function () { return this.data; };

		/** @constructor */
		function asc_CCSVAdvancedOptions(codepage, delimiter, delimiterChar){
			this.codePage = codepage;
			this.delimiter = delimiter;
			this.delimiterChar = delimiterChar;
		}
		asc_CCSVAdvancedOptions.prototype.asc_getDelimiter = function(){return this.delimiter;};
		asc_CCSVAdvancedOptions.prototype.asc_setDelimiter = function(v){this.delimiter = v;};
		asc_CCSVAdvancedOptions.prototype.asc_getDelimiterChar = function(){return this.delimiterChar;};
		asc_CCSVAdvancedOptions.prototype.asc_setDelimiterChar = function(v){this.delimiterChar = v;};
		asc_CCSVAdvancedOptions.prototype.asc_getCodePage = function(){return this.codePage;};
		asc_CCSVAdvancedOptions.prototype.asc_setCodePage = function(v){this.codePage = v;};
		
		/** @constructor */
		function asc_CTXTAdvancedOptions(codepage){
			this.codePage = codepage;
		}
		asc_CTXTAdvancedOptions.prototype.asc_getCodePage = function(){return this.codePage;};
		asc_CTXTAdvancedOptions.prototype.asc_setCodePage = function(v){this.codePage = v;};

		/** @constructor */
		function asc_CDRMAdvancedOptions(password){
			this.password = password;
		}
		asc_CDRMAdvancedOptions.prototype.asc_getPassword = function(){return this.password;};
		asc_CDRMAdvancedOptions.prototype.asc_setPassword = function(v){this.password = v;};

		/** @constructor */
		function asc_CCodePage(){
			this.codePageName = null;
			this.codePage = null;
			this.text = null;
			this.lcid = null;
		}
		asc_CCodePage.prototype.init = function (encoding) {
			this.codePageName = encoding["name"];
			this.codePage = encoding["codepage"];
			this.text = encoding["text"];
			this.lcid = encoding["lcid"];
		};
		asc_CCodePage.prototype.asc_getCodePageName = function(){return this.codePageName;};
		asc_CCodePage.prototype.asc_setCodePageName = function(v){this.codePageName = v;};
		asc_CCodePage.prototype.asc_getCodePage = function(){return this.codePage;};
		asc_CCodePage.prototype.asc_setCodePage = function(v){this.codePage = v;};
		asc_CCodePage.prototype.asc_getText = function(){return this.text;};
		asc_CCodePage.prototype.asc_setText = function(v){this.text = v;};
		asc_CCodePage.prototype.asc_getLcid = function(){return this.lcid;};
		asc_CCodePage.prototype.asc_setLcid = function(v){this.lcid = v;};

		/** @constructor */
		function asc_CDelimiter(delimiter){
			this.delimiterName = delimiter;
		}
		asc_CDelimiter.prototype.asc_getDelimiterName = function(){return this.delimiterName;};
		asc_CDelimiter.prototype.asc_setDelimiterName = function(v){ this.delimiterName = v;};

		/** @constructor */
		function asc_CFormulaGroup(name){
			this.groupName = name;
			this.formulasArray = [];
		}
		asc_CFormulaGroup.prototype.asc_getGroupName = function() { return this.groupName; };
		asc_CFormulaGroup.prototype.asc_getFormulasArray = function() { return this.formulasArray; };
		asc_CFormulaGroup.prototype.asc_addFormulaElement = function(o) { return this.formulasArray.push(o); };

		/** @constructor */
		function asc_CFormula(o){
			this.name = o.name;
		}
		asc_CFormula.prototype.asc_getName = function () {
			return this.name;
		};
		asc_CFormula.prototype.asc_getLocaleName = function () {
			return AscCommonExcel.cFormulaFunctionToLocale ? AscCommonExcel.cFormulaFunctionToLocale[this.name] : this.name;
		};

		//----------------------------------------------------------export----------------------------------------------------
		var prot;
		window['Asc'] = window['Asc'] || {};
		window['AscCommon'] = window['AscCommon'] || {};
		window["AscCommon"].asc_CAdvancedOptions = asc_CAdvancedOptions;
		prot = asc_CAdvancedOptions.prototype;
		prot["asc_getOptionId"]			= prot.asc_getOptionId;
		prot["asc_getOptions"]			= prot.asc_getOptions;

		prot = asc_CCSVOptions.prototype;
		prot["asc_getCodePages"]			= prot.asc_getCodePages;
		prot["asc_getRecommendedSettings"]	= prot.asc_getRecommendedSettings;
		prot["asc_getData"]	= prot.asc_getData;

		prot = asc_CTXTOptions.prototype;
		prot["asc_getCodePages"]			= prot.asc_getCodePages;
		prot["asc_getRecommendedSettings"]	= prot.asc_getRecommendedSettings;
		prot["asc_getData"]	= prot.asc_getData;

		window["Asc"].asc_CCSVAdvancedOptions = window["Asc"]["asc_CCSVAdvancedOptions"] = asc_CCSVAdvancedOptions;
		prot = asc_CCSVAdvancedOptions.prototype;
		prot["asc_getDelimiter"] = prot.asc_getDelimiter;
		prot["asc_setDelimiter"] = prot.asc_setDelimiter;
		prot["asc_getDelimiterChar"] = prot.asc_getDelimiterChar;
		prot["asc_setDelimiterChar"] = prot.asc_setDelimiterChar;
		prot["asc_getCodePage"] = prot.asc_getCodePage;
		prot["asc_setCodePage"] = prot.asc_setCodePage;

		window["Asc"].asc_CTXTAdvancedOptions = window["Asc"]["asc_CTXTAdvancedOptions"] = asc_CTXTAdvancedOptions;
		prot = asc_CTXTAdvancedOptions.prototype;
		prot["asc_getCodePage"] = prot.asc_getCodePage;
		prot["asc_setCodePage"] = prot.asc_setCodePage;

		window["Asc"].asc_CDRMAdvancedOptions = window["Asc"]["asc_CDRMAdvancedOptions"] = asc_CDRMAdvancedOptions;
		prot = asc_CDRMAdvancedOptions.prototype;
		prot["asc_getPassword"] = prot.asc_getPassword;
		prot["asc_setPassword"] = prot.asc_setPassword;

		prot = asc_CCodePage.prototype;
		prot["asc_getCodePageName"]		= prot.asc_getCodePageName;
		prot["asc_setCodePageName"]		= prot.asc_setCodePageName;
		prot["asc_getCodePage"]			= prot.asc_getCodePage;
		prot["asc_setCodePage"]			= prot.asc_setCodePage;
		prot["asc_getText"]				= prot.asc_getText;
		prot["asc_setText"]				= prot.asc_setText;
		prot["asc_getLcid"]				= prot.asc_getLcid;
		prot["asc_setLcid"]				= prot.asc_setLcid;

		prot = asc_CDelimiter.prototype;
		prot["asc_getDelimiterName"]			= prot.asc_getDelimiterName;
		prot["asc_setDelimiterName"]			= prot.asc_setDelimiterName;

		window["AscCommon"].asc_CFormulaGroup = asc_CFormulaGroup;
		prot = asc_CFormulaGroup.prototype;
		prot["asc_getGroupName"]				= prot.asc_getGroupName;
		prot["asc_getFormulasArray"]			= prot.asc_getFormulasArray;
		prot["asc_addFormulaElement"]			= prot.asc_addFormulaElement;

		window["AscCommon"].asc_CFormula = asc_CFormula;
		prot = asc_CFormula.prototype;
		prot["asc_getName"]				= prot.asc_getName;
		prot["asc_getLocaleName"]	= prot.asc_getLocaleName;
	}
)(window);
/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
// Используем [] вместо new Array() для ускорения (http://jsperf.com/creation-array)
// Используем {} вместо new Object() для ускорения (http://jsperf.com/creation-object)

  // Import
  var CColor = AscCommon.CColor;

var c_oAscConfirm = {
  ConfirmReplaceRange: 0,
  ConfirmPutMergeRange: 1
};

var c_oAscMergeOptions = {
  Disabled: -1,
  None: 0,
  Merge: 1,
  MergeCenter: 2,
  MergeAcross: 3
};

var c_oAscSortOptions = {
  Ascending: 1,
  Descending: 2,
  ByColorFill: 3,
  ByColorFont: 4
};

var c_oAscBorderOptions = {
  Top: 0,
  Right: 1,
  Bottom: 2,
  Left: 3,
  DiagD: 4,
  DiagU: 5,
  InnerV: 6,
  InnerH: 7
};

var c_oAscCleanOptions = {
  All: 0,
  Text: 1,
  Format: 2,
  Formula: 4,
  Comments: 5,
  Hyperlinks: 6,
  Sparklines: 7,
  SparklineGroups: 8
};

var c_oAscDrawDepOptions = {
  Master: 0,
  Slave: 1,
  Clear: 2
};

var c_oAscSelectionDialogType = {
  None: 0,
  FormatTable: 1,
  Chart: 2,
  FormatTableChangeRange: 4
};

var c_oAscScrollType = {
  ScrollVertical: 1,
  ScrollHorizontal: 2
};

var c_oAscHyperlinkType = {
  WebLink: 1,
  RangeLink: 2
};

var c_oAscMouseMoveType = {
  None: 0,
  Hyperlink: 1,
  Comment: 2,
  LockedObject: 3,
  ResizeColumn: 4,
  ResizeRow: 5,
  Filter: 6
};

var c_oAscMouseMoveLockedObjectType = {
  None: -1,
  Range: 0,
  TableProperties: 1,
  Sheet: 2
};

var c_oAscLockTypeElem = {
  Range: 1,
  Object: 2,
  Sheet: 3
};

var c_oAscLockTypeElemSubType = {
  DeleteColumns: 1,
  InsertColumns: 2,
  DeleteRows: 3,
  InsertRows: 4,
  ChangeProperties: 5,
  DefinedNames: 6
};

var c_oAscRecalcIndexTypes = {
  RecalcIndexAdd: 1,
  RecalcIndexRemove: 2
};

// Тип печати
var c_oAscPrintType = {
  ActiveSheets: 0,	// Активные листы
  EntireWorkbook: 1,	// Всю книгу
  Selection: 2		// Выделенный фрагмент
};

/** @enum */
var c_oAscCustomAutoFilter = {
  equals: 1,
  isGreaterThan: 2,
  isGreaterThanOrEqualTo: 3,
  isLessThan: 4,
  isLessThanOrEqualTo: 5,
  doesNotEqual: 6,
  beginsWith: 7,
  doesNotBeginWith: 8,
  endsWith: 9,
  doesNotEndWith: 10,
  contains: 11,
  doesNotContain: 12
};

    /** @enum */
var c_oAscDynamicAutoFilter = {
    aboveAverage: 1,
    belowAverage: 2,
    lastMonth: 3,
    lastQuarter: 4,
    lastWeek: 5,
    lastYear: 6,
    m1: 7,
    m10: 8,
    m11: 9,
    m12: 10,
    m2: 11,
    m3: 12,
    m4: 13,
    m5: 14,
    m6: 15,
    m7: 16,
    m8: 17,
    m9: 18,
    nextMonth: 19,
    nextQuarter: 20,
    nextWeek: 21,
    nextYear: 22,
    q1: 23,
    q2: 24,
    q3: 25,
    q4: 26,
    thisMonth: 27,
    thisQuarter: 28,
    thisWeek: 29,
    thisYear: 30,
    today: 31,
    tomorrow: 32,
    yearToDate: 33,
    yesterday: 34
};

var c_oAscTop10AutoFilter = {
    max: 1,
    min: 2
};

var c_oAscChangeFilterOptions = {
  filter: 1,
  style: 2
};

var c_oAscChangeSelectionFormatTable = {
	all: 1,
	data: 2,
	row: 3,
	column: 4
};

var c_oAscChangeTableStyleInfo = {
	columnFirst: 1,
	columnLast: 2,
	columnBanded: 3,
	rowHeader: 4,
	rowTotal: 5,
	rowBanded: 6,
	filterButton: 7,
	advancedSettings: 8
};

// Состояние редактора ячейки
var c_oAscCellEditorState = {
  editEnd: 0,				// Окончание редактирования
  editStart: 1,				// Начало редактирования
  editEmptyCell: 2,			// Редактирование пустой ячейки (доступны функции и свойства текста)
  editText: 3,				// Редактирование текста, числа, даты и др. формата, кроме формулы
  editFormula: 4,			// Редактирование формулы
  editInFormulaBar: 5,		// Редактирование в строке формул
  editInCell: 6				// Редактирование в ячейке
};

// Состояние select-а
var c_oAscCellEditorSelectState = {
  no    : 0,
  char  : 1,
  word  : 2
};

// Пересчитывать ли ширину столбца
var c_oAscCanChangeColWidth = {
  none: 0,	// not recalc
  numbers: 1,	// only numbers
  all: 2	// numbers + text
};

// Merge cell type
var c_oAscMergeType = {
  none: 0,
  columns: 1, // Замержены ли колонки (если да, то автоподбор ширины не должен работать)
  rows: 2     // Замержены ли строки (если да, то автоподбор высоты не должен работать)
};

var c_oAscPaneState = {
  Frozen: "frozen",
  FrozenSplit: "frozenSplit",
  Split: "split"
};

var c_oAscFindLookIn = {
  Formulas: 1,
  Value: 2,
  Annotations: 3
};

var c_oTargetType = {
  None: 0,
  ColumnResize: 1,
  RowResize: 2,
  FillHandle: 3,
  MoveRange: 4,
  MoveResizeRange: 5,
  FilterObject: 6,
  ColumnHeader: 7,
  RowHeader: 8,
  Corner: 9,
  Hyperlink: 10,
  Cells: 11,
  Shape: 12,
  FrozenAnchorH: 14,
  FrozenAnchorV: 15
};

var c_oAscAutoFilterTypes = {
  ColorFilter: 0,
  CustomFilters: 1,
  DynamicFilter: 2,
  Top10: 3,
  Filters: 4,
  None: 5
};

var c_oAscCoAuthoringMeBorderColor = new CColor(22, 156, 0);
var c_oAscCoAuthoringOtherBorderColor = new CColor(238, 53, 37);
var c_oAscCoAuthoringLockTablePropertiesBorderColor = new CColor(255, 144, 0);
var c_oAscCoAuthoringDottedWidth = 4;
var c_oAscCoAuthoringDottedDistance = 2;

var c_oAscFormulaRangeBorderColor = [
  new CColor(95, 140, 237),
  new CColor(235, 94, 96),
  new CColor(141, 97, 194),
  new CColor(45, 150, 57),
  new CColor(191, 76, 145),
  new CColor(227, 130, 34),
  new CColor(55, 127, 158)
];

  var selectionLineType = {
    None        : 0,
    Selection   : 1,
    ActiveCell  : 2,
    Resize      : 4,
    Promote     : 8,
    Dash        : 16
  };

  var c_oAscLockNameFrozenPane = "frozenPane";
  var c_oAscLockNameTabColor = "tabColor";
  var c_oAscLockAddSheet = "addSheet";
  var c_oAscLockLayoutOptions = "layoutOptions";

var c_oAscGetDefinedNamesList = {
  Worksheet: 0,
  WorksheetWorkbook: 1,
  All: 2
};

var c_oAscDefinedNameReason = {
  WrongName: -1,
  IsLocked: -2,
  Existed: -3,
  LockDefNameManager: -4,
  NameReserved: -5,
  OK: 0
};

var c_oAscPopUpSelectorType = {
  None: 0,
  Func: 1,
  Range: 2,
  Table: 3
};
  /** @enum */
  var c_oSerFormat = {
    Version		: 2, //1.0.0.2
    Signature	: "XLSY"
  };

  var c_oAscSparklineType = {
    Line: 0,
    Column: 1,
    Stacked: 2
  };
  var c_oAscEDispBlanksAs = {
    Span: 0,
    Gap: 1,
    Zero: 2
  };
  var c_oAscSparklineAxisMinMax = {
    Individual: 0,
    Group: 1,
    Custom: 2
  };
  var c_oAscAutoCorrectOptions = {
	UndoTableAutoExpansion: 0,
	RedoTableAutoExpansion: 1
  };
  
  var c_kMaxPrintPages = 1500;

  //----------------------------------------------------------export----------------------------------------------------
  window['AscCommonExcel'] = window['AscCommonExcel'] || {};
  window['AscCommonExcel'].c_oAscDrawDepOptions = c_oAscDrawDepOptions;
  window['AscCommonExcel'].c_oAscScrollType = c_oAscScrollType;
  window['AscCommonExcel'].c_oAscLockTypeElem = c_oAscLockTypeElem;
  window['AscCommonExcel'].c_oAscLockTypeElemSubType = c_oAscLockTypeElemSubType;
  window['AscCommonExcel'].c_oAscRecalcIndexTypes = c_oAscRecalcIndexTypes;
  window['AscCommonExcel'].c_oAscCellEditorSelectState = c_oAscCellEditorSelectState;
  window['AscCommonExcel'].c_oAscCanChangeColWidth = c_oAscCanChangeColWidth;
  window['AscCommonExcel'].c_oAscMergeType = c_oAscMergeType;
  window['AscCommonExcel'].c_oAscPaneState = c_oAscPaneState;
  window['AscCommonExcel'].c_oTargetType = c_oTargetType;
  window['AscCommonExcel'].c_oAscCoAuthoringMeBorderColor = c_oAscCoAuthoringMeBorderColor;
  window['AscCommonExcel'].c_oAscCoAuthoringOtherBorderColor = c_oAscCoAuthoringOtherBorderColor;
  window['AscCommonExcel'].c_oAscCoAuthoringLockTablePropertiesBorderColor = c_oAscCoAuthoringLockTablePropertiesBorderColor;
  window['AscCommonExcel'].c_oAscCoAuthoringDottedWidth = c_oAscCoAuthoringDottedWidth;
  window['AscCommonExcel'].c_oAscCoAuthoringDottedDistance = c_oAscCoAuthoringDottedDistance;
  window['AscCommonExcel'].c_oAscFormulaRangeBorderColor = c_oAscFormulaRangeBorderColor;
  window['AscCommonExcel'].selectionLineType = selectionLineType;
  window['AscCommonExcel'].c_oAscLockNameFrozenPane = c_oAscLockNameFrozenPane;
  window['AscCommonExcel'].c_oAscLockNameTabColor = c_oAscLockNameTabColor;
  window['AscCommonExcel'].c_oAscLockAddSheet = c_oAscLockAddSheet;
  window['AscCommonExcel'].c_oAscLockLayoutOptions = c_oAscLockLayoutOptions;
  window['AscCommonExcel'].c_kMaxPrintPages = c_kMaxPrintPages;
  window['AscCommonExcel'].filteringMode = true;

  window['AscCommon'] = window['AscCommon'] || {};
  window['AscCommon'].c_oSerFormat = c_oSerFormat;
  window['AscCommon'].CurFileVersion = c_oSerFormat.Version;

  var prot;
  window['Asc'] = window['Asc'] || {};
  window['Asc']['c_oAscSortOptions'] = window['Asc'].c_oAscSortOptions = c_oAscSortOptions;
  prot = c_oAscSortOptions;
  prot['Ascending'] = prot.Ascending;
  prot['Descending'] = prot.Descending;
  prot['ByColorFill'] = prot.ByColorFill;
  prot['ByColorFont'] = prot.ByColorFont;
  window['Asc']['c_oAscConfirm'] = window['Asc'].c_oAscConfirm = c_oAscConfirm;
  prot = c_oAscConfirm;
  prot['ConfirmReplaceRange'] = prot.ConfirmReplaceRange;
  prot['ConfirmPutMergeRange'] = prot.ConfirmPutMergeRange;
  window['Asc']['c_oAscMergeOptions'] = window['Asc'].c_oAscMergeOptions = c_oAscMergeOptions;
  prot = c_oAscMergeOptions;
  prot['Disabled'] = prot.Disabled;
  prot['None'] = prot.None;
  prot['Merge'] = prot.Merge;
  prot['MergeCenter'] = prot.MergeCenter;
  prot['MergeAcross'] = prot.MergeAcross;
  window['Asc']['c_oAscBorderOptions'] = window['Asc'].c_oAscBorderOptions = c_oAscBorderOptions;
  prot = c_oAscBorderOptions;
  prot['Top'] = prot.Top;
  prot['Right'] = prot.Right;
  prot['Bottom'] = prot.Bottom;
  prot['Left'] = prot.Left;
  prot['DiagD'] = prot.DiagD;
  prot['DiagU'] = prot.DiagU;
  prot['InnerV'] = prot.InnerV;
  prot['InnerH'] = prot.InnerH;
  window['Asc']['c_oAscCleanOptions'] = window['Asc'].c_oAscCleanOptions = c_oAscCleanOptions;
  prot = c_oAscCleanOptions;
  prot['All'] = prot.All;
  prot['Text'] = prot.Text;
  prot['Format'] = prot.Format;
  prot['Formula'] = prot.Formula;
  prot['Comments'] = prot.Comments;
  prot['Hyperlinks'] = prot.Hyperlinks;
  prot['Sparklines'] = prot.Sparklines;
  prot['SparklineGroups'] = prot.SparklineGroups;
  window['Asc']['c_oAscSelectionDialogType'] = window['Asc'].c_oAscSelectionDialogType = c_oAscSelectionDialogType;
  prot = c_oAscSelectionDialogType;
  prot['None'] = prot.None;
  prot['FormatTable'] = prot.FormatTable;
  prot['Chart'] = prot.Chart;
  prot['FormatTableChangeRange'] = prot.FormatTableChangeRange;
  window['Asc']['c_oAscHyperlinkType'] = window['Asc'].c_oAscHyperlinkType = c_oAscHyperlinkType;
  prot = c_oAscHyperlinkType;
  prot['WebLink'] = prot.WebLink;
  prot['RangeLink'] = prot.RangeLink;
  window['Asc']['c_oAscMouseMoveType'] = window['Asc'].c_oAscMouseMoveType = c_oAscMouseMoveType;
  prot = c_oAscMouseMoveType;
  prot['None'] = prot.None;
  prot['Hyperlink'] = prot.Hyperlink;
  prot['Comment'] = prot.Comment;
  prot['LockedObject'] = prot.LockedObject;
  prot['ResizeColumn'] = prot.ResizeColumn;
  prot['ResizeRow'] = prot.ResizeRow;
  prot['Filter'] = prot.Filter;
  window['Asc']['c_oAscMouseMoveLockedObjectType'] = window['Asc'].c_oAscMouseMoveLockedObjectType = c_oAscMouseMoveLockedObjectType;
  prot = c_oAscMouseMoveLockedObjectType;
  prot['None'] = prot.None;
  prot['Range'] = prot.Range;
  prot['TableProperties'] = prot.TableProperties;
  prot['Sheet'] = prot.Sheet;
  window['Asc']['c_oAscPrintType'] = window['Asc'].c_oAscPrintType = c_oAscPrintType;
  prot = c_oAscPrintType;
  prot['ActiveSheets'] = prot.ActiveSheets;
  prot['EntireWorkbook'] = prot.EntireWorkbook;
  prot['Selection'] = prot.Selection;
  window['Asc']['c_oAscCustomAutoFilter'] = window['Asc'].c_oAscCustomAutoFilter = c_oAscCustomAutoFilter;
  prot = c_oAscCustomAutoFilter;
  prot['equals'] = prot.equals;
  prot['isGreaterThan'] = prot.isGreaterThan;
  prot['isGreaterThanOrEqualTo'] = prot.isGreaterThanOrEqualTo;
  prot['isLessThan'] = prot.isLessThan;
  prot['isLessThanOrEqualTo'] = prot.isLessThanOrEqualTo;
  prot['doesNotEqual'] = prot.doesNotEqual;
  prot['beginsWith'] = prot.beginsWith;
  prot['doesNotBeginWith'] = prot.doesNotBeginWith;
  prot['endsWith'] = prot.endsWith;
  prot['doesNotEndWith'] = prot.doesNotEndWith;
  prot['contains'] = prot.contains;
  prot['doesNotContain'] = prot.doesNotContain;
  window['Asc']['c_oAscDynamicAutoFilter'] = window['Asc'].c_oAscDynamicAutoFilter = c_oAscDynamicAutoFilter;
  prot = c_oAscDynamicAutoFilter;
  prot['aboveAverage'] = prot.aboveAverage;
  prot['belowAverage'] = prot.belowAverage;
  window['Asc']['c_oAscTop10AutoFilter'] = window['Asc'].c_oAscTop10AutoFilter = c_oAscTop10AutoFilter;
  prot = c_oAscTop10AutoFilter;
  prot['max'] = prot.max;
  prot['min'] = prot.min;
  window['Asc']['c_oAscChangeFilterOptions'] = window['Asc'].c_oAscChangeFilterOptions = c_oAscChangeFilterOptions;
  prot = c_oAscChangeFilterOptions;
  prot['filter'] = prot.filter;
  prot['style'] = prot.style;
  window['Asc']['c_oAscCellEditorState'] = window['Asc'].c_oAscCellEditorState = c_oAscCellEditorState;
  prot = c_oAscCellEditorState;
  prot['editEnd'] = prot.editEnd;
  prot['editStart'] = prot.editStart;
  prot['editEmptyCell'] = prot.editEmptyCell;
  prot['editText'] = prot.editText;
  prot['editFormula'] = prot.editFormula;
  prot['editInFormulaBar'] = prot.editInFormulaBar;
  prot['editInCell'] = prot.editInCell;
  window['Asc']['c_oAscChangeSelectionFormatTable'] = window['Asc'].c_oAscChangeSelectionFormatTable = c_oAscChangeSelectionFormatTable;
  prot = c_oAscChangeSelectionFormatTable;
  prot['all'] = prot.all;
  prot['data'] = prot.data;
  prot['row'] = prot.row;
  prot['column'] = prot.column;
  window['Asc']['c_oAscChangeTableStyleInfo'] = window['Asc'].c_oAscChangeTableStyleInfo = c_oAscChangeTableStyleInfo;
  prot = c_oAscChangeTableStyleInfo;
  prot['columnFirst'] = prot.columnFirst;
  prot['columnLast'] = prot.columnLast;
  prot['columnBanded'] = prot.columnBanded;
  prot['rowHeader'] = prot.rowHeader;
  prot['rowTotal'] = prot.rowTotal;
  prot['rowBanded'] = prot.rowBanded;
  prot['filterButton'] = prot.filterButton;
  prot['advancedSettings'] = prot.advancedSettings;
  window['Asc']['c_oAscAutoFilterTypes'] = window['Asc'].c_oAscAutoFilterTypes = c_oAscAutoFilterTypes;
  prot = c_oAscAutoFilterTypes;
  prot['ColorFilter'] = prot.ColorFilter;
  prot['CustomFilters'] = prot.CustomFilters;
  prot['DynamicFilter'] = prot.DynamicFilter;
  prot['Top10'] = prot.Top10;
  prot['Filters'] = prot.Filters;
  prot['None'] = prot.None;
  window['Asc']['c_oAscFindLookIn'] = window['Asc'].c_oAscFindLookIn = c_oAscFindLookIn;
  prot = c_oAscFindLookIn;
  prot['Formulas'] = prot.Formulas;
  prot['Value'] = prot.Value;
  prot['Annotations'] = prot.Annotations;
  window['Asc']['c_oAscGetDefinedNamesList'] = window['Asc'].c_oAscGetDefinedNamesList = c_oAscGetDefinedNamesList;
  prot = c_oAscGetDefinedNamesList;
  prot['Worksheet'] = prot.Worksheet;
  prot['WorksheetWorkbook'] = prot.WorksheetWorkbook;
  prot['All'] = prot.All;
  window['Asc']['c_oAscDefinedNameReason'] = window['Asc'].c_oAscDefinedNameReason = c_oAscDefinedNameReason;
  prot = c_oAscDefinedNameReason;
  prot['WrongName'] = prot.WrongName;
  prot['IsLocked'] = prot.IsLocked;
  prot['Existed'] = prot.Existed;
  prot['LockDefNameManager'] = prot.LockDefNameManager;
  prot['NameReserved'] = prot.NameReserved;
  prot['OK'] = prot.OK;
  window['Asc']['c_oAscPopUpSelectorType'] = window['Asc'].c_oAscPopUpSelectorType = c_oAscPopUpSelectorType;
  prot = c_oAscPopUpSelectorType;
  prot['None'] = prot.None;
  prot['Func'] = prot.Func;
  prot['Range'] = prot.Range;
  prot['Table'] = prot.Table;
  window['Asc']['c_oAscSparklineType'] = window['Asc'].c_oAscSparklineType = c_oAscSparklineType;
  prot = c_oAscSparklineType;
  prot['Line'] = prot.Line;
  prot['Column'] = prot.Column;
  prot['Stacked'] = prot.Stacked;
  window['Asc']['c_oAscEDispBlanksAs'] = window['Asc'].c_oAscEDispBlanksAs = c_oAscEDispBlanksAs;
  prot = c_oAscEDispBlanksAs;
  prot['Span'] = prot.Span;
  prot['Gap'] = prot.Gap;
  prot['Zero'] = prot.Zero;
  window['Asc']['c_oAscSparklineAxisMinMax'] = window['Asc'].c_oAscSparklineAxisMinMax = c_oAscSparklineAxisMinMax;
  prot = c_oAscSparklineAxisMinMax;
  prot['Individual'] = prot.Individual;
  prot['Group'] = prot.Group;
  prot['Custom'] = prot.Custom;
  window['Asc']['c_oAscAutoCorrectOptions'] = window['Asc'].c_oAscAutoCorrectOptions = c_oAscAutoCorrectOptions;
  prot = c_oAscAutoCorrectOptions;
  prot['UndoTableAutoExpansion'] = prot.UndoTableAutoExpansion;
  prot['RedoTableAutoExpansion'] = prot.RedoTableAutoExpansion;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
	/**
	 * @param {Window} window
	 * @param {undefined} undefined
	 */
	function (window, undefined) {
		// Import
		var gc_nMaxRow0 = AscCommon.gc_nMaxRow0;
		var gc_nMaxCol0 = AscCommon.gc_nMaxCol0;
		var g_oCellAddressUtils = AscCommon.g_oCellAddressUtils;
		var AscBrowser = AscCommon.AscBrowser;

		var c_oAscSelectionType = Asc.c_oAscSelectionType;

		var c_oAscShiftType = {
			None  : 0,
			Move  : 1,
			Change: 2
		};


		/** @const */
		var kLeftLim1 = .999999999999999;
		var MAX_EXCEL_INT = 1e308;
		var MIN_EXCEL_INT = -MAX_EXCEL_INT;

		/** @const */
		var kUndefinedL = "undefined";
		/** @const */
		var kNullL = "null";
		/** @const */
		var kObjectL = "object";
		/** @const */
		var kFunctionL = "function";
		/** @const */
		var kNumberL = "number";
		/** @const */
		var kArrayL = "array";

		var recalcType = {
			recalc	: 0, // без пересчета
			full		: 1, // пересчитываем все
			newLines: 2  // пересчитываем новые строки

		};

		var sizePxinPt = 72 / 96;

		function applyFunction(callback) {
			if (kFunctionL === typeof callback) {
				callback.apply(null, Array.prototype.slice.call(arguments, 1));
			}
		}

		function typeOf(obj) {
			if (obj === undefined) {return kUndefinedL;}
			if (obj === null) {return kNullL;}
			return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
		}

		function lastIndexOf(s, regExp, fromIndex) {
			var end = fromIndex >= 0 && fromIndex <= s.length ? fromIndex : s.length;
			for (var i = end - 1; i >= 0; --i) {
				var j = s.slice(i, end).search(regExp);
				if (j >= 0) {return i + j;}
			}
			return -1;
		}

		function search(arr, fn) {
			for (var i = 0; i < arr.length; ++i) {
				if ( fn(arr[i]) ) {return i;}
			}
			return -1;
		}

		function getUniqueRangeColor (arrRanges, curElem, tmpColors) {
			var colorIndex, j, range = arrRanges[curElem];
			for (j = 0; j < curElem; ++j) {
				if (range.isEqual(arrRanges[j])) {
					colorIndex = tmpColors[j];
					break;
				}
			}
			return colorIndex;
		}

		function getMinValueOrNull (val1, val2) {
			return null === val2 ? val1 : (null === val1 ? val2 : Math.min(val1, val2));
		}


		function round(x) {
			var y = x + (x >= 0 ? .5 : -.5);
			return y | y;
			//return Math.round(x);
		}

		function floor(x) {
			var y = x | x;
			y -= x < 0 && y > x ? 1 : 0;
			return y + (x - y > kLeftLim1 ? 1 : 0); // to fix float number precision caused by binary presentation
			//return Math.floor(x);
		}

		function ceil(x) {
			var y = x | x;
			y += x > 0 && y < x ? 1 : 0;
			return y - (y - x > kLeftLim1 ? 1 : 0); // to fix float number precision caused by binary presentation
			//return Math.ceil(x);
		}

		function incDecFonSize (bIncrease, oValue) {
			// Закон изменения размеров :
			// Результатом должно быть ближайшее из отрезка [8,72] по следующим числам 8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72
			// Если значение меньше или равно 8 и мы уменьшаем, то ничего не меняется
			// Если значение больше или равно 72 и мы увеличиваем, то ничего не меняется

			var aSizes = [8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72];
			var nLength = aSizes.length;
			var i;
			if (true === bIncrease) {
				if (oValue >= aSizes[nLength - 1])
					return null;
				for (i = 0; i < nLength; ++i)
					if (aSizes[i] > oValue)
						break;
			} else {
				if (oValue <= aSizes[0])
					return null;
				for (i = nLength - 1; i >= 0; --i)
					if (aSizes[i] < oValue)
						break;
			}

			return aSizes[i];
		}

		function calcDecades(num) {
			return Math.abs(num) < 10 ? 1 : 1 + calcDecades(floor(num * 0.1));
		}

		function convertPtToPx(value) {
			value = value / sizePxinPt;
			value = value | value;
			if (AscBrowser.isRetina) {
				value = AscBrowser.convertToRetinaValue(value, true);
			}
			return value;
		}
		function convertPxToPt(value) {
			value = value * sizePxinPt;
			if (AscBrowser.isRetina) {
				value = AscBrowser.convertToRetinaValue(value);
			}
			return value;
		}


		// Определяет времени работы функции
		function profileTime(fn/*[, arguments]*/) {
			var start, end, arg = [], i;
			if (arguments.length) {
				if (arguments.length > 1) {
					for (i = 1; i < arguments.length; ++i)
						arg.push(arguments[i]);
					start = new Date();
					fn.apply(window, arg);
					end = new Date();
				} else {
					start = new Date();
					fn();
					end = new Date();
				}
				return end.getTime() - start.getTime();
			}
			return undefined;
		}

		function getMatchingBorder(border1, border2) {
			// ECMA-376 Part 1 17.4.67 tcBorders (Table Cell Borders)
			if (!border1) {
				return border2;
			}
			if (!border2) {
				return border1;
			}

			if (border1.w > border2.w) {
				return border1;
			} else if (border1.w < border2.w) {
				return border2;
			}

			var r1 = border1.c.getR(), g1 = border1.c.getG(), b1 = border1.c.getB();
			var r2 = border2.c.getR(), g2 = border2.c.getG(), b2 = border2.c.getB();
			var Brightness_1_1 = r1 + b1 + 2 * g1;
			var Brightness_1_2 = r2 + b2 + 2 * g2;
			if (Brightness_1_1 < Brightness_1_2) {
				return border1;
			} else if (Brightness_1_1 > Brightness_1_2) {
				return border2;
			}

			var Brightness_2_1 = Brightness_1_1 - r1;
			var Brightness_2_2 = Brightness_1_2 - r2;
			if (Brightness_2_1 < Brightness_2_2) {
				return border1;
			} else if (Brightness_2_1 > Brightness_2_2) {
				return border2;
			}

			var Brightness_3_1 = g1;
			var Brightness_3_2 = g2;
			if (Brightness_3_1 < Brightness_3_2) {
				return border1;
			} else if (Brightness_3_1 > Brightness_3_2) {
				return border2;
			}

			// borders equal
			return border1;
		}

		var referenceType = {
			A: 0,			// Absolute
			ARRC: 1,	// Absolute row; relative column
			RRAC: 2,	// Relative row; absolute column
			R: 3			// Relative
		};

		/**
		 * Rectangle region of cells
		 * @constructor
		 * @memberOf Asc
		 * @param c1 {Number} Left side of range.
		 * @param r1 {Number} Top side of range.
		 * @param c2 {Number} Right side of range (inclusively).
		 * @param r2 {Number} Bottom side of range (inclusively).
		 * @param normalize {Boolean=} Optional. If true, range will be converted to form (left,top) - (right,bottom).
		 * @return {Range}
		 */
		function Range(c1, r1, c2, r2, normalize) {
			if (!(this instanceof Range)) {
				return new Range(c1, r1, c2, r2, normalize);
			}

			/** @type Number */
			this.c1 = c1;
			/** @type Number */
			this.r1 = r1;
			/** @type Number */
			this.c2 = c2;
			/** @type Number */
			this.r2 = r2;
			this.refType1 = referenceType.R;
			this.refType2 = referenceType.R;

			return normalize ? this.normalize() : this;
		}

		Range.prototype.assign = function (c1, r1, c2, r2, normalize) {
			if (typeOf(c1) !== kNumberL || typeOf(c2) !== kNumberL || typeOf(r1) !== kNumberL || typeOf(r2) !== kNumberL) {
				throw "Error: range.assign(" + c1 + "," + r1 + "," + c2 + "," + r2 + ") - numerical args are expected";
			}
			this.c1 = c1;
			this.r1 = r1;
			this.c2 = c2;
			this.r2 = r2;
			return normalize ? this.normalize() : this;
		};
		Range.prototype.assign2 = function (range) {
			this.refType1 = range.refType1;
			this.refType2 = range.refType2;
			return this.assign(range.c1, range.r1, range.c2, range.r2);
		};

		Range.prototype.clone = function (normalize) {
			var oRes = new Range(this.c1, this.r1, this.c2, this.r2, normalize);
			oRes.refType1 = this.refType1;
			oRes.refType2 = this.refType2;
			return oRes;
		};

		Range.prototype.normalize = function () {
			var tmp;
			if (this.c1 > this.c2) {
				tmp = this.c1;
				this.c1 = this.c2;
				this.c2 = tmp;
			}
			if (this.r1 > this.r2) {
				tmp = this.r1;
				this.r1 = this.r2;
				this.r2 = tmp;
			}
			return this;
		};

		Range.prototype.isEqual = function (range) {
			return range && this.c1 === range.c1 && this.r1 === range.r1 && this.c2 === range.c2 && this.r2 === range.r2;
		};

		Range.prototype.isEqualAll = function (range) {
			return this.isEqual(range) && this.refType1 === range.refType1 && this.refType2 === range.refType2;
		};
		Range.prototype.isEqualWithOffsetRow = function (range, offsetRow) {
			return this.c1 === range.c1 && this.c2 === range.c2 &&
				this.isAbsC1() === range.isAbsC1() && this.isAbsC2() === range.isAbsC2() &&
				this.isAbsR1() === range.isAbsR1() && this.isAbsR2() === range.isAbsR2() &&
				(((this.isAbsR1() ? this.r1 === range.r1 : this.r1 + offsetRow === range.r1) &&
				(this.isAbsR2() ? this.r2 === range.r2 : this.r2 + offsetRow === range.r2)) ||
				(this.r1 === 0 && this.r2 === gc_nMaxRow0 && this.r1 === range.r1 && this.r2 === range.r2));
		};

		Range.prototype.contains = function (c, r) {
			return this.c1 <= c && c <= this.c2 && this.r1 <= r && r <= this.r2;
		};
		Range.prototype.contains2 = function (cell) {
			return this.contains(cell.col, cell.row);
		};

		Range.prototype.containsRange = function (range) {
			return this.contains(range.c1, range.r1) && this.contains(range.c2, range.r2);
		};

		Range.prototype.containsFirstLineRange = function (range) {
			return this.contains(range.c1, range.r1) && this.contains(range.c2, range.r1);
		};

		Range.prototype.intersection = function (range) {
			var s1 = this.clone(true), s2 = range instanceof Range ? range.clone(true) :
				new Range(range.c1, range.r1, range.c2, range.r2, true);

			if (s2.c1 > s1.c2 || s2.c2 < s1.c1 || s2.r1 > s1.r2 || s2.r2 < s1.r1) {
				return null;
			}

			return new Range(s2.c1 >= s1.c1 && s2.c1 <= s1.c2 ? s2.c1 : s1.c1, s2.r1 >= s1.r1 && s2.r1 <= s1.r2 ? s2.r1 :
				s1.r1, Math.min(s1.c2, s2.c2), Math.min(s1.r2, s2.r2));
		};

		Range.prototype.intersectionSimple = function (range) {
			var oRes = null;
			var r1 = Math.max(this.r1, range.r1);
			var c1 = Math.max(this.c1, range.c1);
			var r2 = Math.min(this.r2, range.r2);
			var c2 = Math.min(this.c2, range.c2);
			if (r1 <= r2 && c1 <= c2) {
				oRes = new Range(c1, r1, c2, r2);
			}
			return oRes;
		};

		Range.prototype.isIntersect = function (range) {
			var bRes = true;
			if (range.r2 < this.r1 || this.r2 < range.r1) {
				bRes = false;
			} else if (range.c2 < this.c1 || this.c2 < range.c1) {
				bRes = false;
			}
			return bRes;
		};

		Range.prototype.isIntersectForShift = function(range, offset) {
			var isHor = offset && offset.col;
			var isDelete = offset && (offset.col < 0 || offset.row < 0);
			if (isHor) {
				if (this.r1 <= range.r1 && range.r2 <= this.r2 && this.c1 <= range.c2) {
					return (this.c1 < range.c1 || (!isDelete && this.c1 === range.c1 && this.c2 === range.c1)) ?
						c_oAscShiftType.Move : c_oAscShiftType.Change;
				} else if (isDelete && this.c1 <= range.c1 && range.c2 <= this.c2) {
					var topIn = this.r1 <= range.r1 && range.r1 <= this.r2;
					var bottomIn = this.r1 <= range.r2 && range.r2 <= this.r2;
					return topIn || bottomIn;
				}
			} else {
				if (this.c1 <= range.c1 && range.c2 <= this.c2 && this.r1 <= range.r2) {
					return (this.r1 < range.r1 || (!isDelete && this.r1 === range.r1 && this.r2 === range.r1)) ?
						c_oAscShiftType.Move : c_oAscShiftType.Change;
				} else if (isDelete && this.r1 <= range.r1 && range.r2 <= this.r2) {
					var leftIn = this.c1 <= range.c1 && range.c1 <= this.c2;
					var rightIn = this.c1 <= range.c2 && range.c2 <= this.c2;
					return leftIn || rightIn;
				}
			}
			return c_oAscShiftType.None;
		};

		Range.prototype.difference = function(range) {
			var res = [];
			var intersect;
			if (this.r1 > 0) {
				intersect = new Range(0, 0, gc_nMaxCol0, this.r1 - 1).intersectionSimple(range);
				if (intersect) {
					res.push(intersect);
				}
			}
			if (this.c1 > 0) {
				intersect = new Range(0, this.r1, this.c1 - 1, this.r2).intersectionSimple(range);
				if (intersect) {
					res.push(intersect);
				}
			}
			if (this.c2 < gc_nMaxCol0) {
				intersect = new Range(this.c2 + 1, this.r1, gc_nMaxCol0, this.r2).intersectionSimple(range);
				if (intersect) {
					res.push(intersect);
				}
			}
			if (this.r2 < gc_nMaxRow0) {
				intersect = new Range(0, this.r2 + 1, gc_nMaxCol0, gc_nMaxRow0).intersectionSimple(range);
				if (intersect) {
					res.push(intersect);
				}
			}
			return res;
		};
		Range.prototype.isIntersectForShiftCell = function(col, row, offset) {
			var isHor = offset && 0 != offset.col;
			if (isHor) {
				return this.r1 <= row && row <= this.r2 && this.c1 <= col;
			} else {
				return this.c1 <= col && col <= this.c2 && this.r1 <= row;
			}
		};

		Range.prototype.forShift = function(bbox, offset, bUndo) {
			var isNoDelete = true;
			var isHor = 0 != offset.col;
			var toDelete = offset.col < 0 || offset.row < 0;

			if (isHor) {
				if (toDelete) {
					if (this.c1 < bbox.c1) {
						if (this.c2 <= bbox.c2) {
							this.setOffsetLast(new AscCommon.CellBase(0, -(this.c2 - bbox.c1 + 1)));
						} else {
							this.setOffsetLast(offset);
						}
					} else if (this.c1 <= bbox.c2) {
						if (this.c2 <= bbox.c2) {
							if(!bUndo){
								var topIn = bbox.r1 <= this.r1 && this.r1 <= bbox.r2;
								var bottomIn = bbox.r1 <= this.r2 && this.r2 <= bbox.r2;
								if (topIn && bottomIn) {
									isNoDelete = false;
								} else if (topIn) {
									this.setOffsetFirst(new AscCommon.CellBase(bbox.r2 - this.r1 + 1, 0));
								} else if (bottomIn) {
									this.setOffsetLast(new AscCommon.CellBase(bbox.r1 - this.r2 - 1, 0));
								}
							}
						} else {
							this.setOffsetFirst(new AscCommon.CellBase(0, bbox.c1 - this.c1));
							this.setOffsetLast(offset);
						}
					} else {
						this.setOffset(offset);
					}
				} else {
					if (this.c1 < bbox.c1) {
						this.setOffsetLast(offset);
					} else {
						this.setOffset(offset);
					}
				}
			} else {
				if (toDelete) {
					if (this.r1 < bbox.r1) {
						if (this.r2 <= bbox.r2) {
							this.setOffsetLast(new AscCommon.CellBase(-(this.r2 - bbox.r1 + 1), 0));
						} else {
							this.setOffsetLast(offset);
						}
					} else if (this.r1 <= bbox.r2) {
						if (this.r2 <= bbox.r2) {
							if(!bUndo) {
								var leftIn = bbox.c1 <= this.c1 && this.c1 <= bbox.c2;
								var rightIn = bbox.c1 <= this.c2 && this.c2 <= bbox.c2;
								if (leftIn && rightIn) {
									isNoDelete = false;
								} else if (leftIn) {
									this.setOffsetFirst(new AscCommon.CellBase(0, bbox.c2 - this.c1 + 1));
								} else if (rightIn) {
									this.setOffsetLast(new AscCommon.CellBase(0, bbox.c1 - this.c2 - 1));
								}
							}
						} else {
							this.setOffsetFirst(new AscCommon.CellBase(bbox.r1 - this.r1, 0));
							this.setOffsetLast(offset);
						}
					} else {
						this.setOffset(offset);
					}
				} else {
					if (this.r1 < bbox.r1) {
						this.setOffsetLast(offset);
					} else {
						this.setOffset(offset);
					}
				}
			}
			return isNoDelete;
		};

		Range.prototype.isOneCell = function () {
			return this.r1 === this.r2 && this.c1 === this.c2;
		};

		Range.prototype.isOnTheEdge = function (c, r) {
			return this.r1 === r || this.r2 === r || this.c1 === c || this.c2 === c;
		};

		Range.prototype.union = function (range) {
			var s1 = this.clone(true), s2 = range instanceof Range ? range.clone(true) :
				new Range(range.c1, range.r1, range.c2, range.r2, true);

			return new Range(Math.min(s1.c1, s2.c1), Math.min(s1.r1, s2.r1), Math.max(s1.c2, s2.c2), Math.max(s1.r2, s2.r2));
		};

		Range.prototype.union2 = function (range) {
			this.c1 = Math.min(this.c1, range.c1);
			this.c2 = Math.max(this.c2, range.c2);
			this.r1 = Math.min(this.r1, range.r1);
			this.r2 = Math.max(this.r2, range.r2);
		};

		Range.prototype.union3 = function (c, r) {
			this.c1 = Math.min(this.c1, c);
			this.c2 = Math.max(this.c2, c);
			this.r1 = Math.min(this.r1, r);
			this.r2 = Math.max(this.r2, r);
		};
		Range.prototype.setOffsetWithAbs = function(offset, opt_canResize, opt_circle) {
			var temp;
			var row = offset.row;
			var col = offset.col;
			//todo offset A1048576:A1 (row = 1 -> A1:A2; row = -1 -> A1048575:A1048576)
			if (0 === this.r1 && gc_nMaxRow0 === this.r2) {
				//full sheet is 1:1048576 but row is valid for it
				row = 0;
			} else if (0 === this.c1 && gc_nMaxCol0 === this.c2) {
				col = 0;
			}
			var isAbsRow1 = this.isAbsRow(this.refType1);
			var isAbsCol1 = this.isAbsCol(this.refType1);
			var isAbsRow2 = this.isAbsRow(this.refType2);
			var isAbsCol2 = this.isAbsCol(this.refType2);
			if (!isAbsRow1) {
				this.r1 += row;
				if (this.r1 < 0) {
					if (opt_circle) {
						this.r1 += gc_nMaxRow0 + 1;
					} else {
						this.r1 = 0;
						if (!opt_canResize) {
							return false;
						}
					}
				}
				if (this.r1 > gc_nMaxRow0) {
					if (opt_circle) {
						this.r1 -= gc_nMaxRow0 + 1;
					} else {
						this.r1 = gc_nMaxRow0;
						return false;
					}
				}
			}
			if (!isAbsCol1) {
				this.c1 += col;
				if (this.c1 < 0) {
					if (opt_circle) {
						this.c1 += gc_nMaxCol0 + 1;
					} else {
						this.c1 = 0;
						if (!opt_canResize) {
							return false;
						}
					}
				}
				if (this.c1 > gc_nMaxCol0) {
					if (opt_circle) {
						this.c1 -= gc_nMaxCol0 + 1;
					} else {
						this.c1 = gc_nMaxCol0;
						return false;
					}
				}
			}
			if (!isAbsRow2) {
				this.r2 += row;
				if (this.r2 < 0) {
					if (opt_circle) {
						this.r2 += gc_nMaxRow0 + 1;
					} else {
						this.r2 = 0;
						return false;
					}
				}
				if (this.r2 > gc_nMaxRow0) {
					if (opt_circle) {
						this.r2 -= gc_nMaxRow0 + 1;
					} else {
						this.r2 = gc_nMaxRow0;
						if (!opt_canResize) {
							return false;
						}
					}
				}
			}
			if (!isAbsCol2) {
				this.c2 += col;
				if (this.c2 < 0) {
					if (opt_circle) {
						this.c2 += gc_nMaxCol0 + 1;
					} else {
						this.c2 = 0;
						return false;
					}
				}
				if (this.c2 > gc_nMaxCol0) {
					if (opt_circle) {
						this.c2 -= gc_nMaxCol0 + 1;
					} else {
						this.c2 = gc_nMaxCol0;
						if (!opt_canResize) {
							return false;
						}
					}
				}
			}
			//switch abs flag
			if (this.r1 > this.r2) {
				temp = this.r1;
				this.r1 = this.r2;
				this.r2 = temp;
				if (!isAbsRow1 && isAbsRow2) {
					isAbsRow1 = !isAbsRow1;
					isAbsRow2 = !isAbsRow2;
					this.setAbs(isAbsRow1, isAbsCol1, isAbsRow2, isAbsCol2);
				}
			}
			if (this.c1 > this.c2) {
				temp = this.c1;
				this.c1 = this.c2;
				this.c2 = temp;
				if (!isAbsCol1 && isAbsCol2) {
					isAbsCol1 = !isAbsCol1;
					isAbsCol2 = !isAbsCol2;
					this.setAbs(isAbsRow1, isAbsCol1, isAbsRow2, isAbsCol2);
				}
			}
			return true;
		};
		Range.prototype.setOffset = function (offset) {
			if (this.r1 == 0 && this.r2 == gc_nMaxRow0 && offset.row != 0 ||
				this.c1 == 0 && this.c2 == gc_nMaxCol0 && offset.col != 0) {
				return;
			}
			this.setOffsetFirst(offset);
			this.setOffsetLast(offset);
		};

		Range.prototype.setOffsetFirst = function (offset) {
			this.c1 += offset.col;
			if (this.c1 < 0) {
				this.c1 = 0;
			}
			if (this.c1 > gc_nMaxCol0) {
				this.c1 = gc_nMaxCol0;
			}
			this.r1 += offset.row;
			if (this.r1 < 0) {
				this.r1 = 0;
			}
			if (this.r1 > gc_nMaxRow0) {
				this.r1 = gc_nMaxRow0;
			}
		};

		Range.prototype.setOffsetLast = function (offset) {
			this.c2 += offset.col;
			if (this.c2 < 0) {
				this.c2 = 0;
			}
			if (this.c2 > gc_nMaxCol0) {
				this.c2 = gc_nMaxCol0;
			}
			this.r2 += offset.row;
			if (this.r2 < 0) {
				this.r2 = 0;
			}
			if (this.r2 > gc_nMaxRow0) {
				this.r2 = gc_nMaxRow0;
			}
		};

		Range.prototype._getName = function (val, isCol, abs) {
			var isR1C1Mode = AscCommonExcel.g_R1C1Mode;
			val += 1;
			if (isCol && !isR1C1Mode) {
				val = g_oCellAddressUtils.colnumToColstr(val);
			}
			return (isR1C1Mode ? (isCol ? 'C' : 'R') : '') + (abs ? (isR1C1Mode ? val : '$' + val) :
				(isR1C1Mode ? ((0 !== (val = (val - (isCol ? AscCommonExcel.g_ActiveCell.c1 :
					AscCommonExcel.g_ActiveCell.r1) - 1))) ? '[' + val + ']' : '') : val));
		};
		Range.prototype.getName = function (refType) {
			var isR1C1Mode = AscCommonExcel.g_R1C1Mode;
			var c, r, type = this.getType();
			var sRes = "";
			var c1Abs, c2Abs, r1Abs, r2Abs;
			if (referenceType.A === refType) {
				c1Abs = c2Abs = r1Abs = r2Abs = true;
			} else if (referenceType.R === refType) {
				c1Abs = c2Abs = r1Abs = r2Abs = false;
			} else {
				c1Abs = this.isAbsCol(this.refType1);
				c2Abs = this.isAbsCol(this.refType2);
				r1Abs = this.isAbsRow(this.refType1);
				r2Abs = this.isAbsRow(this.refType2);
			}

			if ((c_oAscSelectionType.RangeMax === type || c_oAscSelectionType.RangeRow === type) && c1Abs === c2Abs) {
				sRes = this._getName(this.r1, false, r1Abs);
				if (this.r1 !== this.r2 || r1Abs !== r2Abs || !isR1C1Mode) {
					sRes += ':' + this._getName(this.r2, false, r2Abs);
				}
			} else if ((c_oAscSelectionType.RangeMax === type || c_oAscSelectionType.RangeCol === type) && r1Abs === r2Abs) {
				sRes = this._getName(this.c1, true, c1Abs);
				if (this.c1 !== this.c2 || c1Abs !== c2Abs || !isR1C1Mode) {
					sRes += ':' + this._getName(this.c2, true, c2Abs);
				}
			} else {
				r = this._getName(this.r1, false, r1Abs);
				c = this._getName(this.c1, true, c1Abs);
				sRes = isR1C1Mode ? r + c : c + r;

				if (!this.isOneCell() || r1Abs !== r2Abs || c1Abs !== c2Abs) {
					r = this._getName(this.r2, false, r2Abs);
					c = this._getName(this.c2, true, c2Abs);
					sRes += ':' + (isR1C1Mode ? r + c : c + r);
				}
			}
			return sRes;
		};

		Range.prototype.getAbsName = function () {
			return this.getName(referenceType.A);
		};

		Range.prototype.getType = function () {
			var bRow = 0 === this.c1 && gc_nMaxCol0 === this.c2;
			var bCol = 0 === this.r1 && gc_nMaxRow0 === this.r2;
			var res;
			if (bCol && bRow) {
				res = c_oAscSelectionType.RangeMax;
			} else if (bCol) {
				res = c_oAscSelectionType.RangeCol;
			} else if (bRow) {
				res = c_oAscSelectionType.RangeRow;
			} else {
				res = c_oAscSelectionType.RangeCells;
			}
			return res;
		};

		Range.prototype.getSharedRange = function (sharedRef, c, r) {
			var isAbsR1 = this.isAbsR1();
			var isAbsC1 = this.isAbsC1();
			var isAbsR2 = this.isAbsR2();
			var isAbsC2 = this.isAbsC2();
			if(this.r1 === 0 && this.r2 === gc_nMaxRow0){
				isAbsR1 = isAbsR2 = true;
			}
			if(this.c1 === 0 && this.c2 === gc_nMaxCol0){
				isAbsC1 = isAbsC2 = true;
			}
			var r1 = isAbsR2 ? sharedRef.r1 : Math.max(sharedRef.r2 + (r - this.r2), sharedRef.r1);
			var c1 = isAbsC2 ? sharedRef.c1 : Math.max(sharedRef.c2 + (c - this.c2), sharedRef.c1);
			var r2 = isAbsR1 ? sharedRef.r2 : Math.min(sharedRef.r1 + (r - this.r1), sharedRef.r2);
			var c2 = isAbsC1 ? sharedRef.c2 : Math.min(sharedRef.c1 + (c - this.c1), sharedRef.c2);
			return new Range(c1, r1, c2, r2);
		};
		Range.prototype.getSharedRangeBbox = function(ref, base) {
			var res = this.clone();
			var shiftBase;
			var offset = new AscCommon.CellBase(ref.r1 - base.nRow, ref.c1 - base.nCol);
			if (!offset.isEmpty()) {
				shiftBase = this.clone();
				shiftBase.setOffsetWithAbs(offset, false, false);
			}
			offset.row = ref.r2 - base.nRow;
			offset.col = ref.c2 - base.nCol;
			res.setOffsetWithAbs(offset, false, false);
			res.union2(shiftBase ? shiftBase : this);
			return res;
		};
		Range.prototype.getSharedIntersect = function(sharedRef, bbox) {
			var leftTop = this.getSharedRange(sharedRef, bbox.c1, bbox.r1);
			var rightBottom = this.getSharedRange(sharedRef, bbox.c2, bbox.r2);
			return leftTop.union(rightBottom);
		};
		Range.prototype.setAbs = function (absRow1, absCol1, absRow2, absCol2) {
			this.refType1 = (absRow1 ? 0 : 2) + (absCol1 ? 0 : 1);
			this.refType2 = (absRow2 ? 0 : 2) + (absCol2 ? 0 : 1);
		};
		Range.prototype.isAbsCol = function (refType) {
			return (refType === referenceType.A || refType === referenceType.RRAC);
		};
		Range.prototype.isAbsRow = function (refType) {
			return (refType === referenceType.A || refType === referenceType.ARRC);
		};
		Range.prototype.isAbsR1 = function () {
			return this.isAbsRow(this.refType1);
		};
		Range.prototype.isAbsC1 = function () {
			return this.isAbsCol(this.refType1);
		};
		Range.prototype.isAbsR2 = function () {
			return this.isAbsRow(this.refType2);
		};
		Range.prototype.isAbsC2 = function () {
			return this.isAbsCol(this.refType2);
		};
		Range.prototype.isAbsAll = function () {
			return this.isAbsR1() && this.isAbsC1() && this.isAbsR2() && this.isAbsC2();
		};
		Range.prototype.switchReference = function () {
			this.refType1 = (this.refType1 + 1) % 4;
			this.refType2 = (this.refType2 + 1) % 4;
		};

		/**
		 *
     * @constructor
		 * @extends {Range}
     */
		function Range3D() {
			this.sheet = '';
			this.sheet2 = '';

			if (3 == arguments.length) {
				var range = arguments[0];
				Range.call(this, range.c1, range.r1, range.c2, range.r2);
				// ToDo стоит пересмотреть конструкторы.
				this.refType1 = range.refType1;
				this.refType2 = range.refType2;

				this.sheet = arguments[1];
				this.sheet2 = arguments[2];
			} else if (arguments.length > 1) {
				Range.apply(this, arguments);
			} else {
				Range.call(this, 0, 0, 0, 0);
      }
		}
		Range3D.prototype = Object.create(Range.prototype);
		Range3D.prototype.constructor = Range3D;
		Range3D.prototype.isIntersect = function () {
			var oRes = true;
			
			if (2 == arguments.length) {
				oRes = this.sheet === arguments[1];
			}
			return oRes && Range.prototype.isIntersect.apply(this, arguments);
		};
		Range3D.prototype.clone = function () {
			return new Range3D(Range.prototype.clone.apply(this, arguments), this.sheet, this.sheet2);
		};
		Range3D.prototype.setSheet = function (sheet, sheet2) {
			this.sheet = sheet;
			this.sheet2 = sheet2 ? sheet2 : sheet;
		};
		Range3D.prototype.getName = function () {
			return AscCommon.parserHelp.get3DRef(this.sheet, Range.prototype.getName.apply(this));
		};

		/**
		 * @constructor
		 */
		function SelectionRange(ws) {
			this.ranges = [new Range(0, 0, 0, 0)];
			this.activeCell = new AscCommon.CellBase(0, 0); // Active cell
			this.activeCellId = 0;

			this.worksheet = ws;
		}

		SelectionRange.prototype.clean = function () {
			this.ranges = [new Range(0, 0, 0, 0)];
			this.activeCellId = 0;
			this.activeCell.clean();
		};
		SelectionRange.prototype.contains = function (c, r) {
			return this.ranges.some(function (item) {
				return item.contains(c, r);
			});
		};
		SelectionRange.prototype.contains2 = function (cell) {
			return this.contains(cell.col, cell.row);
		};
		SelectionRange.prototype.inContains = function (ranges) {
			var t = this;
			return this.ranges.every(function (item1) {
				return ranges.some(function (item2) {
					return item2.containsRange(item1);
				});
			});
		};
		SelectionRange.prototype.containsRange = function (range) {
			return this.ranges.some(function (item) {
				return item.containsRange(range);
			});
		};
		SelectionRange.prototype.clone = function (worksheet) {
			var res = new SelectionRange();
			res.ranges = this.ranges.map(function (range) {
				return range.clone();
			});
			res.activeCell = this.activeCell.clone();
			res.activeCellId = this.activeCellId;
			res.worksheet = worksheet || this.worksheet;
			return res;
		};
		SelectionRange.prototype.isEqual = function (range) {
			if (this.activeCellId !== range.activeCellId || !this.activeCell.isEqual(range.activeCell) ||
				this.ranges.length !== range.ranges.length) {
				return false;
			}
			for (var i = 0; i < this.ranges.length; ++i) {
				if (!this.ranges[i].isEqual(range.ranges[i])) {
					return false;
				}
			}
			return true;
		};
		SelectionRange.prototype.addRange = function () {
			this.activeCellId = this.ranges.push(new Range(0, 0, 0, 0)) - 1;
			this.activeCell.clean();
		};
		SelectionRange.prototype.assign2 = function (range) {
			this.clean();
			this.getLast().assign2(range);
			this.update();
		};
		SelectionRange.prototype.union = function (range) {
			var res = this.ranges.some(function (item) {
				var success = false;
				if (item.c1 === range.c1 && item.c2 === range.c2) {
					if (range.r1 === item.r2 + 1) {
						item.r2 = range.r2;
						success = true;
					} else if (range.r2 === item.r1 - 1) {
						item.r1 = range.r1;
						success = true;
					}
				} else if (item.r1 === range.r1 && item.r2 === range.r2) {
					if (range.c1 === item.c2 + 1) {
						item.c2 = range.c2;
						success = true;
					} else if (range.c2 === item.c1 - 1) {
						item.c1 = range.c1;
						success = true;
					}
				}
				return success;
			});
			if (!res) {
				this.addRange();
				this.getLast().assign2(range);
			}
		};
		SelectionRange.prototype.getUnion = function () {
			var result = new SelectionRange(this.worksheet);
			var unionRanges = function (ranges, res) {
				for (var i = 0; i < ranges.length; ++i) {
					if (0 === i) {
						res.assign2(ranges[i]);
					} else {
						res.union(ranges[i]);
					}
				}
			};
			unionRanges(this.ranges, result);

			var isUnion = true, resultTmp;
			while (isUnion && !result.isSingleRange()) {
				resultTmp = new SelectionRange(this.worksheet);
				unionRanges(result.ranges, resultTmp);
				isUnion = result.ranges.length !== resultTmp.ranges.length;
				result = resultTmp;
			}
			return result;
		};
		SelectionRange.prototype.offsetCell = function (dr, dc, changeRange, fCheckSize) {
			var done, curRange, mc, incompleate;
			// Check one cell
			if (1 === this.ranges.length) {
				curRange = this.ranges[this.activeCellId];
				if (curRange.isOneCell()) {
					return 0;
				} else {
					mc = this.worksheet.getMergedByCell(this.activeCell.row, this.activeCell.col);
					if (mc && curRange.isEqual(mc)) {
						return 0;
					}
				}
			}

			var lastRow = this.activeCell.row;
			var lastCol = this.activeCell.col;
			this.activeCell.row += dr;
			this.activeCell.col += dc;

			while (!done) {
				done = true;

				curRange = this.ranges[this.activeCellId];
				if (!curRange.contains2(this.activeCell)) {
					if (dr) {
						if (0 < dr) {
							this.activeCell.row = curRange.r1;
							this.activeCell.col += 1;
						} else {
							this.activeCell.row = curRange.r2;
							this.activeCell.col -= 1;
						}
					} else {
						if (0 < dc) {
							this.activeCell.row += 1;
							this.activeCell.col = curRange.c1;
						} else {
							this.activeCell.row -= 1;
							this.activeCell.col = curRange.c2;
						}
					}

					if (!curRange.contains2(this.activeCell)) {
						if (!changeRange) {
							this.activeCell.row = lastRow;
							this.activeCell.col = lastCol;
							return -1;
						}
						if (0 < dc || 0 < dr) {
							this.activeCellId += 1;
							this.activeCellId = (this.ranges.length > this.activeCellId) ? this.activeCellId : 0;
							curRange = this.ranges[this.activeCellId];

							this.activeCell.row = curRange.r1;
							this.activeCell.col = curRange.c1;
						} else {
							this.activeCellId -= 1;
							this.activeCellId = (0 <= this.activeCellId) ? this.activeCellId : this.ranges.length - 1;
							curRange = this.ranges[this.activeCellId];

							this.activeCell.row = curRange.r2;
							this.activeCell.col = curRange.c2;
						}
					}
				}

				mc = this.worksheet.getMergedByCell(this.activeCell.row, this.activeCell.col);

				if (mc) {
					incompleate = !curRange.containsRange(mc);
					if (dc > 0 && (incompleate || this.activeCell.col > mc.c1 || this.activeCell.row !== mc.r1)) {
						// Движение слева направо
						this.activeCell.col = mc.c2 + 1;
						done = false;
					} else if (dc < 0 && (incompleate || this.activeCell.col < mc.c2 || this.activeCell.row !== mc.r1)) {
						// Движение справа налево
						this.activeCell.col = mc.c1 - 1;
						done = false;
					}
					if (dr > 0 && (incompleate || this.activeCell.row > mc.r1 || this.activeCell.col !== mc.c1)) {
						// Движение сверху вниз
						this.activeCell.row = mc.r2 + 1;
						done = false;
					} else if (dr < 0 && (incompleate || this.activeCell.row < mc.r2 || this.activeCell.col !== mc.c1)) {
						// Движение снизу вверх
						this.activeCell.row = mc.r1 - 1;
						done = false;
					}
				}
				if (!done) {
					continue;
				}

				while (this.activeCell.col >= curRange.c1 && this.activeCell.col <= curRange.c2 && fCheckSize(-1, this.activeCell.col)) {
					this.activeCell.col += dc || (dr > 0 ? +1 : -1);
					done = false;
				}
				if (!done) {
					continue;
				}

				while (this.activeCell.row >= curRange.r1 && this.activeCell.row <= curRange.r2 && fCheckSize(this.activeCell.row, -1)) {
					this.activeCell.row += dr || (dc > 0 ? +1 : -1);
					done = false;
				}

				if (!done) {
					continue;
				}

				break;
			}
			return (lastRow !== this.activeCell.row || lastCol !== this.activeCell.col) ? 1 : -1;
		};
		SelectionRange.prototype.setCell = function (r, c) {
			var res = false;
			this.activeCell.row = r;
			this.activeCell.col = c;
			this.update();

			// Check active cell in merge cell (bug 36708)
			var mc = this.worksheet.getMergedByCell(this.activeCell.row, this.activeCell.col);
			if (this.worksheet.getMergedByCell(this.activeCell.row, this.activeCell.col)) {
				res = -1 === this.offsetCell(1, 0, false, function () {return false;});
				if (res) {
					this.activeCell.row = mc.r1;
					this.activeCell.col = mc.c1;
				}
			}
			return res;
		};
		SelectionRange.prototype.getLast = function () {
			return this.ranges[this.ranges.length - 1];
		};
		SelectionRange.prototype.isSingleRange = function () {
			return 1 === this.ranges.length;
		};
		SelectionRange.prototype.update = function () {
			//меняем выделеную ячейку, если она не входит в диапазон
			//возможно, в будующем придется пределать логику, пока нет примеров, когда это работает плохо
			var range = this.ranges[this.activeCellId];
			if (!range || !range.contains(this.activeCell.col, this.activeCell.row)) {
				range = this.getLast();
				this.activeCell.col = range.c1;
				this.activeCell.row = range.r1;
				this.activeCellId = this.ranges.length - 1;
			}
		};
		SelectionRange.prototype.WriteToBinary = function(w) {
			w.WriteLong(this.ranges.length);
			for (var i = 0; i < this.ranges.length; ++i) {
				var range = this.ranges[i];
				w.WriteLong(range.c1);
				w.WriteLong(range.r1);
				w.WriteLong(range.c2);
				w.WriteLong(range.r2);
			}
			w.WriteLong(this.activeCell.row);
			w.WriteLong(this.activeCell.col);
			w.WriteLong(this.activeCellId);
		};
		SelectionRange.prototype.ReadFromBinary = function(r) {
			this.clean();
			var count = r.GetLong();
			var rangesNew = [];
			for (var i = 0; i < count; ++i) {
				var range = new Asc.Range(r.GetLong(), r.GetLong(), r.GetLong(), r.GetLong());
				rangesNew.push(range);
			}
			if (rangesNew.length > 0) {
				this.ranges = rangesNew;
			}
			this.activeCell.row = r.GetLong();
			this.activeCell.col = r.GetLong();
			this.activeCellId = r.GetLong();
			this.update();
		};
		SelectionRange.prototype.Select = function () {
			this.worksheet.selectionRange = this.clone();
			this.worksheet.workbook.handlers.trigger('updateSelection');
		};

    /**
     *
     * @constructor
     * @extends {Range}
     */
		function ActiveRange(){
			if(1 == arguments.length)
			{
				var range = arguments[0];
				Range.call(this, range.c1, range.r1, range.c2, range.r2);
				// ToDo стоит пересмотреть конструкторы.
				this.refType1 = range.refType1;
				this.refType2 = range.refType2;
			}
			else if(arguments.length > 1)
				Range.apply(this, arguments);
			else
				Range.call(this, 0, 0, 0, 0);
			this.startCol = 0; // Активная ячейка в выделении
			this.startRow = 0; // Активная ячейка в выделении
			this._updateAdditionalData();
		}

		ActiveRange.prototype = Object.create(Range.prototype);
		ActiveRange.prototype.constructor = ActiveRange;
		ActiveRange.prototype.assign = function () {
			Range.prototype.assign.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.assign2 = function () {
			Range.prototype.assign2.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.clone = function(){
			var oRes = new ActiveRange(Range.prototype.clone.apply(this, arguments));
			oRes.startCol = this.startCol;
			oRes.startRow = this.startRow;
			return oRes;
		};
		ActiveRange.prototype.normalize = function () {
			Range.prototype.normalize.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.isEqualAll = function () {
			var bRes = Range.prototype.isEqual.apply(this, arguments);
			if(bRes && arguments.length > 0)
			{
				var range = arguments[0];
				bRes = this.startCol == range.startCol && this.startRow == range.startRow;
			}
			return bRes;
		};
		ActiveRange.prototype.contains = function () {
			return Range.prototype.contains.apply(this, arguments);
		};
		ActiveRange.prototype.containsRange = function () {
			return Range.prototype.containsRange.apply(this, arguments);
		};
		ActiveRange.prototype.containsFirstLineRange = function () {
			return Range.prototype.containsFirstLineRange.apply(this, arguments);
		};
		ActiveRange.prototype.intersection = function () {
			var oRes = Range.prototype.intersection.apply(this, arguments);
			if(null != oRes)
			{
				oRes = new ActiveRange(oRes);
				oRes._updateAdditionalData();
			}
			return oRes;
		};
		ActiveRange.prototype.intersectionSimple = function () {
			var oRes = Range.prototype.intersectionSimple.apply(this, arguments);
			if(null != oRes)
			{
				oRes = new ActiveRange(oRes);
				oRes._updateAdditionalData();
			}
			return oRes;
		};
		ActiveRange.prototype.union = function () {
			var oRes = new ActiveRange(Range.prototype.union.apply(this, arguments));
			oRes._updateAdditionalData();
			return oRes;
		};
		ActiveRange.prototype.union2 = function () {
			Range.prototype.union2.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.union3 = function () {
			Range.prototype.union3.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.setOffset = function(offset){
			this.setOffsetFirst(offset);
			this.setOffsetLast(offset);
		};
		ActiveRange.prototype.setOffsetFirst = function(offset){
			Range.prototype.setOffsetFirst.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype.setOffsetLast = function(offset){
			Range.prototype.setOffsetLast.apply(this, arguments);
			this._updateAdditionalData();
			return this;
		};
		ActiveRange.prototype._updateAdditionalData = function(){
			//меняем выделеную ячейку, если она не входит в диапазон
			//возможно, в будующем придется пределать логику, пока нет примеров, когда это работает плохо
			if(!this.contains(this.startCol, this.startRow))
			{
				this.startCol = this.c1;
				this.startRow = this.r1;
			}
		};

    /**
     *
     * @constructor
     * @extends {Range}
     */
		function FormulaRange(){
			if(1 == arguments.length)
			{
				var range = arguments[0];
				Range.call(this, range.c1, range.r1, range.c2, range.r2);
			}
			else if(arguments.length > 1)
				Range.apply(this, arguments);
			else
				Range.call(this, 0, 0, 0, 0);

			this.refType1 = referenceType.R;
			this.refType2 = referenceType.R;
		}

		FormulaRange.prototype = Object.create(Range.prototype);
		FormulaRange.prototype.constructor = FormulaRange;
		FormulaRange.prototype.clone = function () {
			var oRes = new FormulaRange(Range.prototype.clone.apply(this, arguments));
			oRes.refType1 = this.refType1;
			oRes.refType2 = this.refType2;
			return oRes;
		};
		FormulaRange.prototype.intersection = function () {
			var oRes = Range.prototype.intersection.apply(this, arguments);
			if(null != oRes)
				oRes = new FormulaRange(oRes);
			return oRes;
		};
		FormulaRange.prototype.intersectionSimple = function () {
			var oRes = Range.prototype.intersectionSimple.apply(this, arguments);
			if(null != oRes)
				oRes = new FormulaRange(oRes);
			return oRes;
		};
		FormulaRange.prototype.union = function () {
			return new FormulaRange(Range.prototype.union.apply(this, arguments));
		};
		FormulaRange.prototype.getName = function () {
			var sRes = "";
			var c1Abs = this.isAbsCol(this.refType1), c2Abs = this.isAbsCol(this.refType2);
			var r1Abs = this.isAbsRow(this.refType1), r2Abs = this.isAbsRow(this.refType2);

			if(0 == this.c1 && gc_nMaxCol0 == this.c2)
			{
				if(r1Abs)
					sRes += "$";
				sRes += (this.r1 + 1) + ":";
				if(r2Abs)
					sRes += "$";
				sRes += (this.r2 + 1);
			}
			else if(0 == this.r1 && gc_nMaxRow0 == this.r2)
			{
				if(c1Abs)
					sRes += "$";
				sRes += g_oCellAddressUtils.colnumToColstr(this.c1 + 1) + ":";
				if(c2Abs)
					sRes += "$";
				sRes += g_oCellAddressUtils.colnumToColstr(this.c2 + 1);
			}
			else
			{
				if(c1Abs)
					sRes += "$";
				sRes += g_oCellAddressUtils.colnumToColstr(this.c1 + 1);
				if(r1Abs)
					sRes += "$";
				sRes += (this.r1 + 1);
				if(!this.isOneCell())
				{
					sRes += ":";
					if(c2Abs)
						sRes += "$";
					sRes += g_oCellAddressUtils.colnumToColstr(this.c2 + 1);
					if(r2Abs)
						sRes += "$";
					sRes += (this.r2 + 1);
				}
			}
			return sRes;
		};

		function MultiplyRange(ranges) {
			this.ranges = ranges;
		}
		MultiplyRange.prototype.clone = function() {
			return new MultiplyRange(this.ranges.slice());
		};
		MultiplyRange.prototype.union2 = function(multiplyRange) {
			this.ranges = this.ranges.concat(multiplyRange.ranges);
		};
		MultiplyRange.prototype.isIntersect = function(range) {
			for (var i = 0; i < this.ranges.length; ++i) {
				if (range.isIntersect(this.ranges[i])) {
					return true;
				}
			}
			return false;
		};
		MultiplyRange.prototype.contains = function(c, r) {
			for (var i = 0; i < this.ranges.length; ++i) {
				if (this.ranges[i].contains(c, r)) {
					return true;
				}
			}
			return false;
		};

		function VisibleRange(visibleRange, offsetX, offsetY) {
			this.visibleRange = visibleRange;
			this.offsetX = offsetX;
			this.offsetY = offsetY;
		}

		function RangeCache() {
			this.oCache = {};
		}

		RangeCache.prototype.getAscRange = function (sRange) {
			return this._getRange(sRange, 1);
		};
		RangeCache.prototype.getRange3D = function (sRange) {
			var res = AscCommon.parserHelp.parse3DRef(sRange);
			if (!res) {
				return null;
			}
			var range = this._getRange(res.range.toUpperCase(), 1);
			return range ? new Range3D(range, res.sheet, res.sheet2) : null;
		};
		RangeCache.prototype.getActiveRange = function (sRange) {
			return this._getRange(sRange, 2);
		};
		RangeCache.prototype.getActiveRangesFromSqRef = function (sqRef) {
			var res = [];
			var refs = sqRef.split(' ');
			for (var i = 0; i < refs.length; ++i) {
				var ref = AscCommonExcel.g_oRangeCache.getAscRange(refs[i]);
				if (ref) {
					res.push(ref.clone());
				}
			}
			return res;
		};
		RangeCache.prototype.getFormulaRange = function (sRange) {
			return this._getRange(sRange, 3);
		};
		RangeCache.prototype._getRange = function (sRange, type) {
			if (AscCommonExcel.g_R1C1Mode) {
				var o = {
					Formula: sRange, pCurrPos: 0
				};
				if (AscCommon.parserHelp.isArea.call(o, o.Formula, o.pCurrPos)) {
					sRange = o.real_str;
				} else if (AscCommon.parserHelp.isRef.call(o, o.Formula, o.pCurrPos)) {
					sRange = o.real_str;
				}
			}
			var oRes = null;
			var oCacheVal = this.oCache[sRange];
			if (null == oCacheVal) {
				var oFirstAddr, oLastAddr;
				var bIsSingle = true;
				var nIndex = sRange.indexOf(":");
				if (-1 != nIndex) {
					bIsSingle = false;
					oFirstAddr = g_oCellAddressUtils.getCellAddress(sRange.substring(0, nIndex));
					oLastAddr = g_oCellAddressUtils.getCellAddress(sRange.substring(nIndex + 1));
				} else {
					oFirstAddr = oLastAddr = g_oCellAddressUtils.getCellAddress(sRange);
				}
				oCacheVal = {first: null, last: null, ascRange: null, formulaRange: null, activeRange: null};
				//последнее условие, чтобы не распознавалось "A", "1"(должно быть "A:A", "1:1")
				if (oFirstAddr.isValid() && oLastAddr.isValid() &&
					(!bIsSingle || (!oFirstAddr.getIsRow() && !oFirstAddr.getIsCol()))) {
					oCacheVal.first = oFirstAddr;
					oCacheVal.last = oLastAddr;
				}
				this.oCache[sRange] = oCacheVal;
			}
			if (1 == type) {
				oRes = oCacheVal.ascRange;
			} else if (2 == type) {
				oRes = oCacheVal.activeRange;
			} else {
				oRes = oCacheVal.formulaRange;
			}
			if (null == oRes && null != oCacheVal.first && null != oCacheVal.last) {
				var r1 = oCacheVal.first.getRow0(), r2 = oCacheVal.last.getRow0(), c1 = oCacheVal.first.getCol0(), c2 = oCacheVal.last.getCol0();
				var r1Abs = oCacheVal.first.getRowAbs(), r2Abs = oCacheVal.last.getRowAbs(),
					c1Abs = oCacheVal.first.getColAbs(), c2Abs = oCacheVal.last.getColAbs();
				if (oCacheVal.first.getIsRow() && oCacheVal.last.getIsRow()) {
					c1 = 0;
					c2 = gc_nMaxCol0;
				}
				if (oCacheVal.first.getIsCol() && oCacheVal.last.getIsCol()) {
					r1 = 0;
					r2 = gc_nMaxRow0;
				}
				if (r1 > r2) {
					var temp = r1;
					r1 = r2;
					r2 = temp;
					temp = r1Abs;
					r1Abs = r2Abs;
					r2Abs = temp;
				}
				if (c1 > c2) {
					var temp = c1;
					c1 = c2;
					c2 = temp;
					temp = c1Abs;
					c1Abs = c2Abs;
					c2Abs = temp;
				}

				if (1 == type) {
					if (null == oCacheVal.ascRange) {
						var oAscRange = new Range(c1, r1, c2, r2);
						oAscRange.setAbs(r1Abs, c1Abs, r2Abs, c2Abs);

						oCacheVal.ascRange = oAscRange;
					}
					oRes = oCacheVal.ascRange;
				} else if (2 == type) {
					if (null == oCacheVal.activeRange) {
						var oActiveRange = new ActiveRange(c1, r1, c2, r2);
						oActiveRange.setAbs(r1Abs, c1Abs, r2Abs, c2Abs);
						oActiveRange.startCol = oActiveRange.c1;
						oActiveRange.startRow = oActiveRange.r1;
						oCacheVal.activeRange = oActiveRange;
					}
					oRes = oCacheVal.activeRange;
				} else {
					if (null == oCacheVal.formulaRange) {
						var oFormulaRange = new FormulaRange(c1, r1, c2, r2);
						oFormulaRange.setAbs(r1Abs, c1Abs, r2Abs, c2Abs);

						oCacheVal.formulaRange = oFormulaRange;
					}
					oRes = oCacheVal.formulaRange;
				}
			}
			return oRes;
		};

		var g_oRangeCache = new RangeCache();
		/**
		 * @constructor
		 * @memberOf Asc
		 */
		function HandlersList(handlers) {
			if ( !(this instanceof HandlersList) ) {return new HandlersList(handlers);}
			this.handlers = handlers || {};
			return this;
		}

		HandlersList.prototype = {

			constructor: HandlersList,

			trigger: function (eventName) {
				var h = this.handlers[eventName], t = typeOf(h), a = Array.prototype.slice.call(arguments, 1), i;
				if (t === kFunctionL) {
					return h.apply(this, a);
				}
				if (t === kArrayL) {
					for (i = 0; i < h.length; i += 1) {
						if (typeOf(h[i]) === kFunctionL) {h[i].apply(this, a);}
					}
					return true;
				}
				return false;
			},

			add: function (eventName, eventHandler, replaceOldHandler) {
				var th = this.handlers, h, old, t;
				if (replaceOldHandler || !th.hasOwnProperty(eventName)) {
					th[eventName] = eventHandler;
				} else {
					old = h = th[eventName];
					t = typeOf(old);
					if (t !== kArrayL) {
						h = th[eventName] = [];
						if (t === kFunctionL) {h.push(old);}
					}
					h.push(eventHandler);
				}
			},

			remove: function (eventName, eventHandler) {
				var th = this.handlers, h = th[eventName], i;
				if (th.hasOwnProperty(eventName)) {
					if (typeOf(h) !== kArrayL || typeOf(eventHandler) !== kFunctionL) {
						delete th[eventName];
						return true;
					}
					for (i = h.length - 1; i >= 0; i -= 1) {
						if (h[i] === eventHandler) {
							delete h[i];
							return true;
						}
					}
				}
				return false;
			}

		};


		function outputDebugStr(channel) {
			var c = window.console;
			if (Asc.g_debug_mode && c && c[channel] && c[channel].apply) {
				c[channel].apply(this, Array.prototype.slice.call(arguments, 1));
			}
		}
		
		function trim(val)
		{
			if(!String.prototype.trim)
				return val.trim();
			else
				return val.replace(/^\s+|\s+$/g,'');  
		}

		function isNumberInfinity(val) {
		    var valTrim = trim(val);
		    var valInt = valTrim - 0;
		    return valInt == valTrim && valTrim.length > 0 && MIN_EXCEL_INT < valInt && valInt < MAX_EXCEL_INT;//
		}

		function arrayToLowerCase(array) {
			var result = [];
			for (var i = 0, length = array.length; i < length; ++i)
				result.push(array[i].toLowerCase());
			return result;
		}

		function isFixedWidthCell(frag) {
			for (var i = 0; i < frag.length; ++i) {
				var f = frag[i].format;
				if (f && f.getRepeat()) {return true;}
			}
			return false;
		}

		function dropDecimalAutofit(f) {
			var s = getFragmentsText(f);
			// Проверка scientific format
			if (s.search(/E/i) >= 0) {
				return f;
			}
			// Поиск десятичной точки
			var pos = s.indexOf(AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator);
			if (-1 !== pos) {
				f = [f[0].clone()];
				f[0].text = s.slice(0, pos);
			}
			return f;
		}

		function getFragmentsText(f) {
			return f.reduce(function (pv, cv) {
				return pv + cv.text;
			}, "");
		}

		function executeInR1C1Mode(mode, runFunction) {
			var oldMode = AscCommonExcel.g_R1C1Mode;
			AscCommonExcel.g_R1C1Mode = mode;
			runFunction();
			AscCommonExcel.g_R1C1Mode = oldMode;
		}

		function getEndValueRange (dx, start, v1, v2) {
			var x1, x2;
			if (0 !== dx) {
				if (start === v1) {
					x1 = v1;
					x2 = v2;
				} else if (start === v2) {
					x1 = v2;
					x2 = v1;
				} else {
					if (0 > dx) {
						x1 = v2;
						x2 = v1;
					} else {
						x1 = v1;
						x2 = v2;
					}
				}
			} else {
				x1 = v1;
				x2 = v2;
			}
			return {x1: x1, x2: x2};
		}

		//-----------------------------------------------------------------
		// События движения мыши
		//-----------------------------------------------------------------
		/** @constructor */
		function asc_CMouseMoveData (obj) {
			if ( !(this instanceof asc_CMouseMoveData) ) {
				return new asc_CMouseMoveData(obj);
			}
			
			if (obj) {
				this.type = obj.type;
				this.x = obj.x;
				this.reverseX = obj.reverseX;	// Отображать комментарий слева от ячейки
				this.y = obj.y;
				this.hyperlink = obj.hyperlink;
				this.aCommentIndexes = obj.aCommentIndexes;
				this.userId = obj.userId;
				this.lockedObjectType = obj.lockedObjectType;

				// Для resize
				this.sizeCCOrPt = obj.sizeCCOrPt;
				this.sizePx = obj.sizePx;

				//Filter
				this.filter = obj.filter;
			}

			return this;
		}
		asc_CMouseMoveData.prototype = {
			constructor: asc_CMouseMoveData,
			asc_getType: function () { return this.type; },
			asc_getX: function () { return this.x; },
			asc_getReverseX: function () { return this.reverseX; },
			asc_getY: function () { return this.y; },
			asc_getHyperlink: function () { return this.hyperlink; },
			asc_getCommentIndexes: function () { return this.aCommentIndexes; },
			asc_getUserId: function () { return this.userId; },
			asc_getLockedObjectType: function () { return this.lockedObjectType; },
			asc_getSizeCCOrPt: function () { return this.sizeCCOrPt; },
			asc_getSizePx: function () { return this.sizePx; },
			asc_getFilter: function () { return this.filter; }
		};

		// Гиперссылка
		/** @constructor */
		function asc_CHyperlink (obj) {
			if (!(this instanceof asc_CHyperlink)) {
				return new asc_CHyperlink(obj);
			}

			// Класс Hyperlink из модели
			this.hyperlinkModel = null != obj ? obj : new AscCommonExcel.Hyperlink();
			// Используется только для выдачи наружу и выставлении обратно
			this.text = null;

			return this;
		}
		asc_CHyperlink.prototype = {
			constructor: asc_CHyperlink,
			asc_getType: function () { return this.hyperlinkModel.getHyperlinkType(); },
			asc_getHyperlinkUrl: function () { return this.hyperlinkModel.Hyperlink; },
			asc_getTooltip: function () { return this.hyperlinkModel.Tooltip; },
			asc_getLocation: function () { return this.hyperlinkModel.getLocation(); },
			asc_getSheet: function () { return this.hyperlinkModel.LocationSheet; },
			asc_getRange: function () {return this.hyperlinkModel.getLocationRange();},
			asc_getText: function () { return this.text; },

			asc_setType: function (val) {
				// В принципе эта функция избыточна
				switch (val) {
					case Asc.c_oAscHyperlinkType.WebLink:
						this.hyperlinkModel.setLocation(null);
						break;
					case Asc.c_oAscHyperlinkType.RangeLink:
						this.hyperlinkModel.Hyperlink = null;
						break;
				}
			},
			asc_setHyperlinkUrl: function (val) { this.hyperlinkModel.Hyperlink = val; },
			asc_setTooltip: function (val) { this.hyperlinkModel.Tooltip = val ? val.slice(0, Asc.c_oAscMaxTooltipLength) : val; },
			asc_setLocation: function (val) { this.hyperlinkModel.setLocation(val); },
			asc_setSheet: function (val) { this.hyperlinkModel.setLocationSheet(val); },
			asc_setRange: function (val) { this.hyperlinkModel.setLocationRange(val); },
			asc_setText: function (val) { this.text = val; }
		};

		function CPagePrint() {
			this.pageWidth = 0;
			this.pageHeight = 0;

			this.pageClipRectLeft = 0;
			this.pageClipRectTop = 0;
			this.pageClipRectWidth = 0;
			this.pageClipRectHeight = 0;

			this.pageRange = null;

			this.leftFieldInPx = 0;
			this.topFieldInPx = 0;

			this.pageGridLines = false;
			this.pageHeadings = false;

			this.indexWorksheet = -1;

			this.startOffset = 0;
			this.startOffsetPx = 0;

			return this;
		}
		function CPrintPagesData () {
			this.arrPages = [];
			this.currentIndex = 0;

			return this;
		}
		/** @constructor */
		function asc_CAdjustPrint () {
			// Вид печати
			this.printType = Asc.c_oAscPrintType.ActiveSheets;
			this.pageOptionsMap = null;

			// ToDo сюда же start и end page index

			return this;
		}
		asc_CAdjustPrint.prototype.asc_getPrintType = function () { return this.printType; };
		asc_CAdjustPrint.prototype.asc_setPrintType = function (val) { this.printType = val; };
		asc_CAdjustPrint.prototype.asc_getPageOptionsMap = function () { return this.pageOptionsMap; };
		asc_CAdjustPrint.prototype.asc_setPageOptionsMap = function (val) { this.pageOptionsMap = val; };

		/** @constructor */
		function asc_CLockInfo () {
			this["sheetId"] = null;
			this["type"] = null;
			this["subType"] = null;
			this["guid"] = null;
			this["rangeOrObjectId"] = null;
		}

		/** @constructor */
		function asc_CCollaborativeRange (c1, r1, c2, r2) {
			this["c1"] = c1;
			this["r1"] = r1;
			this["c2"] = c2;
			this["r2"] = r2;
		}

		/** @constructor */
		function asc_CSheetViewSettings () {
			// Показывать ли сетку
			this.showGridLines = null;
			// Показывать обозначения строк и столбцов
			this.showRowColHeaders = null;

			// Закрепление области
			this.pane = null;

			//current view zoom
			this.zoomScale = 100;

			return this;
		}

		asc_CSheetViewSettings.prototype = {
			constructor: asc_CSheetViewSettings,
			clone: function () {
				var result = new asc_CSheetViewSettings();
				result.showGridLines = this.showGridLines;
				result.showRowColHeaders = this.showRowColHeaders;
				result.zoom = this.zoom;
				if (this.pane)
					result.pane = this.pane.clone();
				return result;
			},
			isEqual: function (settings) {
				return this.asc_getShowGridLines() === settings.asc_getShowGridLines() &&
					this.asc_getShowRowColHeaders() === settings.asc_getShowRowColHeaders();
			},
			asc_getShowGridLines: function () { return false !== this.showGridLines; },
			asc_getShowRowColHeaders: function () { return false !== this.showRowColHeaders; },
			asc_getZoomScale: function () { return this.zoomScale; },
			asc_getIsFreezePane: function () { return null !== this.pane && this.pane.isInit(); },
			asc_setShowGridLines: function (val) { this.showGridLines = val; },
			asc_setShowRowColHeaders: function (val) { this.showRowColHeaders = val; },
			asc_setZoomScale: function (val) { this.zoomScale = val; }
		};

		/** @constructor */
		function asc_CPane () {
			this.state = null;
			this.topLeftCell = null;
			this.xSplit = 0;
			this.ySplit = 0;
			// CellAddress для удобства
			this.topLeftFrozenCell = null;

			return this;
		}
		asc_CPane.prototype.isInit = function () {
			return null !== this.topLeftFrozenCell;
		};
		asc_CPane.prototype.clone = function() {
			var res = new asc_CPane();
			res.state = this.state;
			res.topLeftCell = this.topLeftCell;
			res.xSplit = this.xSplit;
			res.ySplit = this.ySplit;
			res.topLeftFrozenCell = this.topLeftFrozenCell ?
				new AscCommon.CellAddress(this.topLeftFrozenCell.row, this.topLeftFrozenCell.col) : null;
			return res;
		};
		asc_CPane.prototype.init = function() {
			// ToDo Обрабатываем пока только frozen и frozenSplit
			if ((AscCommonExcel.c_oAscPaneState.Frozen === this.state || AscCommonExcel.c_oAscPaneState.FrozenSplit === this.state) &&
				(0 < this.xSplit || 0 < this.ySplit)) {
				this.topLeftFrozenCell = new AscCommon.CellAddress(this.ySplit, this.xSplit, 0);
				if (!this.topLeftFrozenCell.isValid())
					this.topLeftFrozenCell = null;
			}
		};

		function RedoObjectParam () {
			this.bIsOn = false;
			this.bIsReInit = false;
			this.oChangeWorksheetUpdate = {};
			this.bUpdateWorksheetByModel = false;
			this.bOnSheetsChanged = false;
			this.oOnUpdateTabColor = {};
			this.oOnUpdateSheetViewSettings = {};
			this.bAddRemoveRowCol = false;
			this.bChangeActive = false;
			this.activeSheet = null;
		}


		/** @constructor */
		function asc_CStylesPainter(width, height) {
			this.defaultStyles = null;
			this.docStyles = null;

			this.styleThumbnailWidth = width;
			this.styleThumbnailHeight = height;
			this.styleThumbnailWidthPt = this.styleThumbnailWidth * 72 / 96;
			this.styleThumbnailHeightPt = this.styleThumbnailHeight * 72 / 96;

			this.styleThumbnailWidthWithRetina = this.styleThumbnailWidth;
			this.styleThumbnailHeightWithRetina = this.styleThumbnailHeight;
			if (AscCommon.AscBrowser.isRetina) {
				this.styleThumbnailWidthWithRetina =
					AscCommon.AscBrowser.convertToRetinaValue(this.styleThumbnailWidthWithRetina, true);
				this.styleThumbnailHeightWithRetina =
					AscCommon.AscBrowser.convertToRetinaValue(this.styleThumbnailHeightWithRetina, true);
			}
		}

		asc_CStylesPainter.prototype.asc_checkStylesNames = function(cellStylesAll) {
			var oStyle, i;
			for (i = 0; i < cellStylesAll.DefaultStyles.length; ++i) {
				oStyle = cellStylesAll.DefaultStyles[i];
				AscFonts.FontPickerByCharacter.getFontsByString(oStyle.Name);
				AscFonts.FontPickerByCharacter.getFontsByString(AscCommon.translateManager.getValue(oStyle.Name));
			}
			for (i = 0; i < cellStylesAll.CustomStyles.length; ++i) {
				oStyle = cellStylesAll.CustomStyles[i];
				AscFonts.FontPickerByCharacter.getFontsByString(oStyle.Name);
			}
		};
		asc_CStylesPainter.prototype.asc_getStyleThumbnailWidth = function () {
			return this.styleThumbnailWidthWithRetina;
		};
		asc_CStylesPainter.prototype.asc_getStyleThumbnailHeight = function () {
			return this.styleThumbnailHeightWithRetina;
		};
		asc_CStylesPainter.prototype.asc_getDefaultStyles = function () {
			return this.defaultStyles;
		};
		asc_CStylesPainter.prototype.asc_getDocStyles = function () {
			return this.docStyles;
		};
		asc_CStylesPainter.prototype.generateStylesAll = function (cellStylesAll, fmgrGraphics, oFont, sr) {
			this.generateDefaultStyles(cellStylesAll, fmgrGraphics, oFont, sr);
			this.generateDocumentStyles(cellStylesAll, fmgrGraphics, oFont, sr);
		};
		asc_CStylesPainter.prototype.generateDefaultStyles = function (cellStylesAll, fmgrGraphics, oFont, sr) {
			var cellStyles = cellStylesAll.DefaultStyles;

			var oCanvas = document.createElement('canvas');
			oCanvas.width = this.styleThumbnailWidthWithRetina;
			oCanvas.height = this.styleThumbnailHeightWithRetina;
			var oGraphics = new Asc.DrawingContext(
				{canvas: oCanvas, units: 1/*pt*/, fmgrGraphics: fmgrGraphics, font: oFont});

			var oStyle, oCustomStyle;
			this.defaultStyles = [];
			for (var i = 0; i < cellStyles.length; ++i) {
				oStyle = cellStyles[i];
				if (oStyle.Hidden) {
					continue;
				}
				// ToDo Возможно стоит переписать немного, чтобы не пробегать каждый раз по массиву custom-стилей (нужно генерировать AllStyles)
				oCustomStyle = cellStylesAll.getCustomStyleByBuiltinId(oStyle.BuiltinId);

				this.drawStyle(oGraphics, sr, oCustomStyle || oStyle, AscCommon.translateManager.getValue(oStyle.Name));
				this.defaultStyles.push(new AscCommon.CStyleImage(oStyle.Name, AscCommon.c_oAscStyleImage.Default,
					oCanvas.toDataURL("image/png")));
			}
		};
		asc_CStylesPainter.prototype.generateDocumentStyles = function (cellStylesAll, fmgrGraphics, oFont, sr) {
			var cellStyles = cellStylesAll.CustomStyles;

			var oCanvas = document.createElement('canvas');
			oCanvas.width = this.styleThumbnailWidthWithRetina;
			oCanvas.height = this.styleThumbnailHeightWithRetina;
			var oGraphics = new Asc.DrawingContext(
				{canvas: oCanvas, units: 1/*pt*/, fmgrGraphics: fmgrGraphics, font: oFont});

			var oStyle;
			this.docStyles = [];
			for (var i = 0; i < cellStyles.length && i < 1000; ++i) {
				oStyle = cellStyles[i];
				if (oStyle.Hidden || null != oStyle.BuiltinId) {
					continue;
				}

				this.drawStyle(oGraphics, sr, oStyle, oStyle.Name);
				this.docStyles.push(new AscCommon.CStyleImage(oStyle.Name, AscCommon.c_oAscStyleImage.Document,
					oCanvas.toDataURL("image/png")));
			}
		};
		asc_CStylesPainter.prototype.drawStyle = function (oGraphics, sr, oStyle, sStyleName) {
			oGraphics.clear();
			// Fill cell
			var oColor = oStyle.getFill();
			if (null !== oColor) {
				oGraphics.setFillStyle(oColor);
				oGraphics.fillRect(0, 0, this.styleThumbnailWidthPt, this.styleThumbnailHeightPt);
			}

			var drawBorder = function (b, x1, y1, x2, y2) {
				if (b && AscCommon.c_oAscBorderStyles.None !== b.s) {
					oGraphics.setStrokeStyle(b.c);

					// ToDo поправить
					oGraphics.setLineWidth(b.w).beginPath().moveTo(x1, y1).lineTo(x2, y2).stroke();
				}
			};

			// borders
			var oBorders = oStyle.getBorder();
			drawBorder(oBorders.l, 0, 0, 0, this.styleThumbnailHeightPt);
			drawBorder(oBorders.r, this.styleThumbnailWidthPt, 0, this.styleThumbnailWidthPt,
				this.styleThumbnailHeightPt);
			drawBorder(oBorders.t, 0, 0, this.styleThumbnailWidthPt, 0);
			drawBorder(oBorders.b, 0, this.styleThumbnailHeightPt, this.styleThumbnailWidthPt,
				this.styleThumbnailHeightPt);

			// Draw text
			var fc = oStyle.getFontColor();
			var oFontColor = fc !== null ? fc : new AscCommon.CColor(0, 0, 0);
			var format = oStyle.getFont();
			var fs = format.getSize();
			// Для размера шрифта делаем ограничение для превью в 16pt (у Excel 18pt, но и высота превью больше 22px)
			var oFont = new Asc.FontProperties(format.getName(), (16 < fs) ? 16 : fs, format.getBold(),
				format.getItalic(), format.getUnderline(), format.getStrikeout());

			var width_padding = 3; // 4 * 72 / 96

			var tm = sr.measureString(sStyleName);
			// Текст будем рисовать по центру (в Excel чуть по другому реализовано, у них постоянный отступ снизу)
			var textY = 0.5 * (this.styleThumbnailHeightPt - tm.height);
			oGraphics.setFont(oFont);
			oGraphics.setFillStyle(oFontColor);
			oGraphics.fillText(sStyleName, width_padding, textY + tm.baseline);
		};

		/** @constructor */
		function asc_CSheetPr() {
			if (!(this instanceof asc_CSheetPr)) {
				return new asc_CSheetPr();
			}

			this.CodeName = null;
			this.EnableFormatConditionsCalculation = null;
			this.FilterMode = null;
			this.Published = null;
			this.SyncHorizontal = null;
			this.SyncRef = null;
			this.SyncVertical = null;
			this.TransitionEntry = null;
			this.TransitionEvaluation = null;

			this.TabColor = null;

			return this;
		}
		asc_CSheetPr.prototype.clone = function()  {
			var res = new asc_CSheetPr();

			res.CodeName = this.CodeName;
			res.EnableFormatConditionsCalculation = this.EnableFormatConditionsCalculation;
			res.FilterMode = this.FilterMode;
			res.Published = this.Published;
			res.SyncHorizontal = this.SyncHorizontal;
			res.SyncRef = this.SyncRef;
			res.SyncVertical = this.SyncVertical;
			res.TransitionEntry = this.TransitionEntry;
			res.TransitionEvaluation = this.TransitionEvaluation;
			if (this.TabColor)
				res.TabColor = this.TabColor.clone();

			return res;
		};

		// Математическая информация о выделении
		/** @constructor */
		function asc_CSelectionMathInfo() {
			this.count = 0;
			this.countNumbers = 0;
			this.sum = null;
			this.average = null;
			this.min = null;
			this.max = null;
		}

		asc_CSelectionMathInfo.prototype = {
			constructor: asc_CSelectionMathInfo,
			asc_getCount: function () { return this.count; },
			asc_getCountNumbers: function () { return this.countNumbers; },
			asc_getSum: function () { return this.sum; },
			asc_getAverage: function () { return this.average; },
			asc_getMin: function () { return this.min; },
			asc_getMax: function () { return this.max; }
		};

		/** @constructor */
		function asc_CFindOptions() {
			this.findWhat = "";							// текст, который ищем
			this.scanByRows = true;						// просмотр по строкам/столбцам
			this.scanForward = true;					// поиск вперед/назад
			this.isMatchCase = false;					// учитывать регистр
			this.isWholeCell = false;					// ячейка целиком
			this.scanOnOnlySheet = true;				// искать только на листе/в книге
			this.lookIn = Asc.c_oAscFindLookIn.Formulas;	// искать в формулах/значениях/примечаниях

			this.replaceWith = "";						// текст, на который заменяем (если у нас замена)
			this.isReplaceAll = false;					// заменить все (если у нас замена)

			// внутренние переменные
			this.findInSelection = false;
			this.selectionRange = null;
			this.findRange = null;
			this.findResults = null;
			this.indexInArray = 0;
			this.countFind = 0;
			this.countReplace = 0;
			this.countFindAll = 0;
			this.countReplaceAll = 0;
			this.sheetIndex = -1;
			this.error = false;
		}
		asc_CFindOptions.prototype.clone = function () {
			var result = new asc_CFindOptions();
			result.findWhat = this.findWhat;
			result.scanByRows = this.scanByRows;
			result.scanForward = this.scanForward;
			result.isMatchCase = this.isMatchCase;
			result.isWholeCell = this.isWholeCell;
			result.scanOnOnlySheet = this.scanOnOnlySheet;
			result.lookIn = this.lookIn;

			result.replaceWith = this.replaceWith;
			result.isReplaceAll = this.isReplaceAll;

			result.findInSelection = this.findInSelection;
			result.selectionRange = this.selectionRange ? this.selectionRange.clone() : null;
			result.findRange = this.findRange ? this.findRange.clone() : null;
			result.indexInArray = this.indexInArray;
			result.countFind = this.countFind;
			result.countReplace = this.countReplace;
			result.countFindAll = this.countFindAll;
			result.countReplaceAll = this.countReplaceAll;
			result.sheetIndex = this.sheetIndex;
			result.error = this.error;
			return result;
		};
		asc_CFindOptions.prototype.isEqual = function (obj) {
			return obj && this.isEqual2(obj) && this.scanForward === obj.scanForward &&
				this.scanOnOnlySheet === obj.scanOnOnlySheet;
		};
		asc_CFindOptions.prototype.isEqual2 = function (obj) {
			return obj && this.findWhat === obj.findWhat && this.scanByRows === obj.scanByRows &&
				this.isMatchCase === obj.isMatchCase && this.isWholeCell === obj.isWholeCell &&
				this.lookIn === obj.lookIn;
		};
		asc_CFindOptions.prototype.clearFindAll = function () {
			this.countFindAll = 0;
			this.countReplaceAll = 0;
			this.error = false;
		};
		asc_CFindOptions.prototype.updateFindAll = function () {
			this.countFindAll += this.countFind;
			this.countReplaceAll += this.countReplace;
		};

		asc_CFindOptions.prototype.asc_setFindWhat = function (val) {this.findWhat = val;};
		asc_CFindOptions.prototype.asc_setScanByRows = function (val) {this.scanByRows = val;};
		asc_CFindOptions.prototype.asc_setScanForward = function (val) {this.scanForward = val;};
		asc_CFindOptions.prototype.asc_setIsMatchCase = function (val) {this.isMatchCase = val;};
		asc_CFindOptions.prototype.asc_setIsWholeCell = function (val) {this.isWholeCell = val;};
		asc_CFindOptions.prototype.asc_setScanOnOnlySheet = function (val) {this.scanOnOnlySheet = val;};
		asc_CFindOptions.prototype.asc_setLookIn = function (val) {this.lookIn = val;};
		asc_CFindOptions.prototype.asc_setReplaceWith = function (val) {this.replaceWith = val;};
		asc_CFindOptions.prototype.asc_setIsReplaceAll = function (val) {this.isReplaceAll = val;};

		/** @constructor */
		function findResults() {
			this.values = {};

			this.currentKey1 = -1;
			this.currentKey2 = -1;
			this.currentKeys1 = null;
			this.currentKeys2 = null;
		}

		findResults.prototype.isNotEmpty = function () {
			return 0 !== Object.keys(this.values).length;
		};
		findResults.prototype.contains = function (key1, key2) {
			return this.values[key1] && this.values[key1][key2];
		};
		findResults.prototype.add = function (key1, key2, cell) {
			if (!this.values[key1]) {
				this.values[key1] = {};
			}
			this.values[key1][key2] = cell;
		};
		findResults.prototype._init = function (key1, key2) {
			this.currentKey1 = key1;
			this.currentKey2 = key2;
			this.currentKeyIndex1 = -1;
			this.currentKeyIndex2 = -1;

			this.currentKeys2 = null;
			this.currentKeys1 = Object.keys(this.values).sort(AscCommon.fSortAscending);
			this.currentKeyIndex1 = this._findKey(this.currentKey1, this.currentKeys1);
			if (0 === this.currentKeys1[this.currentKeyIndex1] - this.currentKey1) {
				this.currentKeys2 = Object.keys(this.values[this.currentKey1]).sort(AscCommon.fSortAscending);
				this.currentKeyIndex2 = this._findKey(this.currentKey2, this.currentKeys2);
			}
		};
		findResults.prototype.find = function (key1, key2, forward) {
			this.forward = forward;

			if (this.currentKey1 !== key1 || this.currentKey2 !== key2) {
				this._init(key1, key2);
			}

			if (0 === this.currentKeys1.length) {
				return false;
			}

			var step = this.forward ? +1 : -1;
			this.currentKeyIndex2 += step;
			if (!this.currentKeys2 || !this.currentKeys2[this.currentKeyIndex2]) {
				this.currentKeyIndex1 += step;
				if (!this.currentKeys1[this.currentKeyIndex1]) {
					this.currentKeyIndex1 = this.forward ? 0 : this.currentKeys1.length - 1;
				}
				this.currentKey1 = this.currentKeys1[this.currentKeyIndex1] >> 0;
				this.currentKeys2 = Object.keys(this.values[this.currentKey1]).sort(AscCommon.fSortAscending);
				this.currentKeyIndex2 = this.forward ? 0 : this.currentKeys2.length - 1;
			}
			this.currentKey2 = this.currentKeys2[this.currentKeyIndex2] >> 0;
			return true;
		};
		findResults.prototype._findKey = function (key, arrayKeys) {
			var i = this.forward ? 0 : arrayKeys.length - 1;
			var step = this.forward ? +1 : -1;
			var _key;
			while (_key = arrayKeys[i]) {
				_key = step * ((_key >> 0) - key);
				if (_key >= 0) {
					return 0 === _key ? i : (i - step);
				}
				i += step;
			}
			return -2;
		};

		/** @constructor */
		function asc_CCompleteMenu(name, type) {
			this.name = name;
			this.type = type;
		}
		asc_CCompleteMenu.prototype.asc_getName = function () {return this.name;};
		asc_CCompleteMenu.prototype.asc_getType = function () {return this.type;};

		function CCacheMeasureEmpty() {
			this.cache = {};
		}
		CCacheMeasureEmpty.prototype.add = function (elem, val) {
			var fn = elem.getName();
			var font = (this.cache[fn] || (this.cache[fn] = {}));
			font[elem.getSize()] = val;
		};
		CCacheMeasureEmpty.prototype.get = function (elem) {
			var font = this.cache[elem.getName()];
			return font ? font[elem.getSize()] : null;
		};
		var g_oCacheMeasureEmpty = new CCacheMeasureEmpty();

		/** @constructor */
		function asc_CFormatCellsInfo() {
			this.type = Asc.c_oAscNumFormatType.General;
			this.decimalPlaces = 2;
			this.separator = false;
			this.symbol = null;
		}
		asc_CFormatCellsInfo.prototype.asc_setType = function (val) {this.type = val;};
		asc_CFormatCellsInfo.prototype.asc_setDecimalPlaces = function (val) {this.decimalPlaces = val;};
		asc_CFormatCellsInfo.prototype.asc_setSeparator = function (val) {this.separator = val;};
		asc_CFormatCellsInfo.prototype.asc_setSymbol = function (val) {this.symbol = val;};
		asc_CFormatCellsInfo.prototype.asc_getType = function () {return this.type;};
		asc_CFormatCellsInfo.prototype.asc_getDecimalPlaces = function () {return this.decimalPlaces;};
		asc_CFormatCellsInfo.prototype.asc_getSeparator = function () {return this.separator;};
		asc_CFormatCellsInfo.prototype.asc_getSymbol = function () {return this.symbol;};

		function asc_CSelectionRangeValue(){
			this.name =  null;
			this.type = null;
		}
		asc_CSelectionRangeValue.prototype.asc_setType = function (val) {this.type = val;};
		asc_CSelectionRangeValue.prototype.asc_setName = function (val) {this.name = val;};
		asc_CSelectionRangeValue.prototype.asc_getType = function () {return this.type;};
		asc_CSelectionRangeValue.prototype.asc_getName = function () {return this.name;};

		//передаём в меню для того, чтобы показать иконку опций авторавертывания таблиц
		function asc_CAutoCorrectOptions(){
			this.type = null;
			this.options = [];
			this.cellCoord = null;
		}
		asc_CAutoCorrectOptions.prototype.asc_setType = function (val) {this.type = val;};
		asc_CAutoCorrectOptions.prototype.asc_setOptions = function (val) {this.options = val;};
		asc_CAutoCorrectOptions.prototype.asc_setCellCoord = function(val) { this.cellCoord = val; };
		asc_CAutoCorrectOptions.prototype.asc_getType = function () {return this.type;};
		asc_CAutoCorrectOptions.prototype.asc_getOptions = function () {return this.options;};
		asc_CAutoCorrectOptions.prototype.asc_getCellCoord = function () {return this.cellCoord;};

		/*
		 * Export
		 * -----------------------------------------------------------------------------
		 */
		var prot;
		window['Asc'] = window['Asc'] || {};
		window['AscCommonExcel'] = window['AscCommonExcel'] || {};
		window['AscCommonExcel'].g_ActiveCell = null; // Active Cell for calculate (in R1C1 mode for relative cell)
		window['AscCommonExcel'].g_R1C1Mode = false; // No calculate in R1C1 mode
		window["AscCommonExcel"].c_oAscShiftType = c_oAscShiftType;
		window["AscCommonExcel"].recalcType = recalcType;
		window["AscCommonExcel"].sizePxinPt = sizePxinPt;
		window["AscCommonExcel"].applyFunction = applyFunction;
		window["Asc"].typeOf = typeOf;
		window["Asc"].lastIndexOf = lastIndexOf;
		window["Asc"].search = search;
		window["Asc"].getUniqueRangeColor = getUniqueRangeColor;
		window["Asc"].getMinValueOrNull = getMinValueOrNull;
		window["Asc"].round = round;
		window["Asc"].floor = floor;
		window["Asc"].ceil = ceil;
		window["Asc"].incDecFonSize = incDecFonSize;
		window["AscCommonExcel"].calcDecades = calcDecades;
		window["AscCommonExcel"].convertPtToPx = convertPtToPx;
		window["AscCommonExcel"].convertPxToPt = convertPxToPt;
		window["Asc"].outputDebugStr = outputDebugStr;
		window["Asc"].profileTime = profileTime;
		window["AscCommonExcel"].getMatchingBorder = getMatchingBorder;
		window["Asc"].isNumberInfinity = isNumberInfinity;
		window["Asc"].trim = trim;
		window["Asc"].arrayToLowerCase = arrayToLowerCase;
		window["Asc"].isFixedWidthCell = isFixedWidthCell;
		window["AscCommonExcel"].dropDecimalAutofit = dropDecimalAutofit;
		window["AscCommonExcel"].getFragmentsText = getFragmentsText;
		window['AscCommonExcel'].executeInR1C1Mode = executeInR1C1Mode;
		window["Asc"].getEndValueRange = getEndValueRange;

		window["AscCommonExcel"].referenceType = referenceType;
		window["Asc"].Range = Range;
		window["AscCommonExcel"].Range3D = Range3D;
		window["AscCommonExcel"].SelectionRange = SelectionRange;
		window["AscCommonExcel"].ActiveRange = ActiveRange;
		window["AscCommonExcel"].FormulaRange = FormulaRange;
		window["AscCommonExcel"].MultiplyRange = MultiplyRange;
		window["AscCommonExcel"].VisibleRange = VisibleRange;
		window["AscCommonExcel"].g_oRangeCache = g_oRangeCache;

		window["AscCommonExcel"].HandlersList = HandlersList;

		window["AscCommonExcel"].RedoObjectParam = RedoObjectParam;

		window["AscCommonExcel"].asc_CMouseMoveData = asc_CMouseMoveData;
		prot = asc_CMouseMoveData.prototype;
		prot["asc_getType"] = prot.asc_getType;
		prot["asc_getX"] = prot.asc_getX;
		prot["asc_getReverseX"] = prot.asc_getReverseX;
		prot["asc_getY"] = prot.asc_getY;
		prot["asc_getHyperlink"] = prot.asc_getHyperlink;		
		prot["asc_getCommentIndexes"] = prot.asc_getCommentIndexes;
		prot["asc_getUserId"] = prot.asc_getUserId;
		prot["asc_getLockedObjectType"] = prot.asc_getLockedObjectType;
		prot["asc_getSizeCCOrPt"] = prot.asc_getSizeCCOrPt;
		prot["asc_getSizePx"] = prot.asc_getSizePx;
		prot["asc_getFilter"] = prot.asc_getFilter;

		window["Asc"]["asc_CHyperlink"] = window["Asc"].asc_CHyperlink = asc_CHyperlink;
		prot = asc_CHyperlink.prototype;
		prot["asc_getType"] = prot.asc_getType;
		prot["asc_getHyperlinkUrl"] = prot.asc_getHyperlinkUrl;
		prot["asc_getTooltip"] = prot.asc_getTooltip;
		prot["asc_getLocation"] = prot.asc_getLocation;
		prot["asc_getSheet"] = prot.asc_getSheet;
		prot["asc_getRange"] = prot.asc_getRange;
		prot["asc_getText"] = prot.asc_getText;
		prot["asc_setType"] = prot.asc_setType;
		prot["asc_setHyperlinkUrl"] = prot.asc_setHyperlinkUrl;
		prot["asc_setTooltip"] = prot.asc_setTooltip;
		prot["asc_setLocation"] = prot.asc_setLocation;
		prot["asc_setSheet"] = prot.asc_setSheet;
		prot["asc_setRange"] = prot.asc_setRange;
		prot["asc_setText"] = prot.asc_setText;

		window["AscCommonExcel"].CPagePrint = CPagePrint;
		window["AscCommonExcel"].CPrintPagesData = CPrintPagesData;

		window["Asc"]["asc_CAdjustPrint"] = window["Asc"].asc_CAdjustPrint = asc_CAdjustPrint;
		prot = asc_CAdjustPrint.prototype;
		prot["asc_getPrintType"] = prot.asc_getPrintType;
		prot["asc_setPrintType"] = prot.asc_setPrintType;
		prot["asc_getPageOptionsMap"] = prot.asc_getPageOptionsMap;
		prot["asc_setPageOptionsMap"] = prot.asc_setPageOptionsMap;

		window["AscCommonExcel"].asc_CLockInfo = asc_CLockInfo;

		window["AscCommonExcel"].asc_CCollaborativeRange = asc_CCollaborativeRange;

		window["AscCommonExcel"].asc_CSheetViewSettings = asc_CSheetViewSettings;
		prot = asc_CSheetViewSettings.prototype;
		prot["asc_getShowGridLines"] = prot.asc_getShowGridLines;
		prot["asc_getShowRowColHeaders"] = prot.asc_getShowRowColHeaders;
		prot["asc_getIsFreezePane"] = prot.asc_getIsFreezePane;
		prot["asc_setShowGridLines"] = prot.asc_setShowGridLines;
		prot["asc_setShowRowColHeaders"] = prot.asc_setShowRowColHeaders;

		window["AscCommonExcel"].asc_CPane = asc_CPane;

		window["AscCommonExcel"].asc_CStylesPainter = asc_CStylesPainter;
		prot = asc_CStylesPainter.prototype;
		prot["asc_getStyleThumbnailWidth"] = prot.asc_getStyleThumbnailWidth;
		prot["asc_getStyleThumbnailHeight"] = prot.asc_getStyleThumbnailHeight;
		prot["asc_getDefaultStyles"] = prot.asc_getDefaultStyles;
		prot["asc_getDocStyles"] = prot.asc_getDocStyles;

		window["AscCommonExcel"].asc_CSheetPr = asc_CSheetPr;

		window["AscCommonExcel"].asc_CSelectionMathInfo = asc_CSelectionMathInfo;
		prot = asc_CSelectionMathInfo.prototype;
		prot["asc_getCount"] = prot.asc_getCount;
		prot["asc_getCountNumbers"] = prot.asc_getCountNumbers;
		prot["asc_getSum"] = prot.asc_getSum;
		prot["asc_getAverage"] = prot.asc_getAverage;
		prot["asc_getMin"] = prot.asc_getMin;
		prot["asc_getMax"] = prot.asc_getMax;

		window["Asc"]["asc_CFindOptions"] = window["Asc"].asc_CFindOptions = asc_CFindOptions;
		prot = asc_CFindOptions.prototype;
		prot["asc_setFindWhat"] = prot.asc_setFindWhat;
		prot["asc_setScanByRows"] = prot.asc_setScanByRows;
		prot["asc_setScanForward"] = prot.asc_setScanForward;
		prot["asc_setIsMatchCase"] = prot.asc_setIsMatchCase;
		prot["asc_setIsWholeCell"] = prot.asc_setIsWholeCell;
		prot["asc_setScanOnOnlySheet"] = prot.asc_setScanOnOnlySheet;
		prot["asc_setLookIn"] = prot.asc_setLookIn;
		prot["asc_setReplaceWith"] = prot.asc_setReplaceWith;
		prot["asc_setIsReplaceAll"] = prot.asc_setIsReplaceAll;

		window["AscCommonExcel"].findResults = findResults;

		window["AscCommonExcel"].asc_CCompleteMenu = asc_CCompleteMenu;
		prot = asc_CCompleteMenu.prototype;
		prot["asc_getName"] = prot.asc_getName;
		prot["asc_getType"] = prot.asc_getType;

		window["AscCommonExcel"].g_oCacheMeasureEmpty = g_oCacheMeasureEmpty;

		window["Asc"]["asc_CFormatCellsInfo"] = window["Asc"].asc_CFormatCellsInfo = asc_CFormatCellsInfo;
		prot = asc_CFormatCellsInfo.prototype;
		prot["asc_setType"] = prot.asc_setType;
		prot["asc_setDecimalPlaces"] = prot.asc_setDecimalPlaces;
		prot["asc_setSeparator"] = prot.asc_setSeparator;
		prot["asc_setSymbol"] = prot.asc_setSymbol;
		prot["asc_getType"] = prot.asc_getType;
		prot["asc_getDecimalPlaces"] = prot.asc_getDecimalPlaces;
		prot["asc_getSeparator"] = prot.asc_getSeparator;
		prot["asc_getSymbol"] = prot.asc_getSymbol;

		window["AscCommonExcel"]["asc_CSelectionRangeValue"] = window["AscCommonExcel"].asc_CSelectionRangeValue = asc_CSelectionRangeValue;
		prot = asc_CSelectionRangeValue.prototype;
		prot["asc_getType"] = prot.asc_getType;
		prot["asc_getName"] = prot.asc_getName;

		window["Asc"]["asc_CAutoCorrectOptions"] = window["Asc"].asc_CAutoCorrectOptions = asc_CAutoCorrectOptions;
		prot = asc_CAutoCorrectOptions.prototype;
		prot["asc_getType"] = prot.asc_getType;
		prot["asc_getOptions"] = prot.asc_getOptions;
		prot["asc_getCellCoord"] = prot.asc_getCellCoord;

})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(
	/**
	 * @param {Window} window
	 * @param {undefined} undefined
	 */
	function (window, undefined) {
		/*
		 * Import
		 * -----------------------------------------------------------------------------
		*/
		var asc = window["Asc"],
			asc_typeOf = asc.typeOf;


		/** @constructor */
		function asc_CHandlersList(handlers) {
			this.handlers = handlers || {};
			return this;
		}

		asc_CHandlersList.prototype.hasTrigger = function (eventName) {
			return null != this.handlers[eventName];
		};

		asc_CHandlersList.prototype.trigger = function (eventName) {
			var h = this.handlers[eventName], t = asc_typeOf(h), a = Array.prototype.slice.call(arguments, 1), i;
			if (t === "function") {
				return h.apply(this, a);
			}
			if (t === "array") {
				for (i = 0; i < h.length; i += 1) {
					if (asc_typeOf(h[i]) === "function") {h[i].apply(this, a);}
				}
				return true;
			}
			return false;
		};
		asc_CHandlersList.prototype.add = function (eventName, eventHandler, replaceOldHandler) {
			var th = this.handlers, h, old, t;
			if (replaceOldHandler || !th.hasOwnProperty(eventName)) {
				th[eventName] = eventHandler;
			} else {
				old = h = th[eventName];
				t = asc_typeOf(old);
				if (t !== "array") {
					h = th[eventName] = [];
					if (t === "function") {h.push(old);}
				}
				h.push(eventHandler);
			}
		};
		asc_CHandlersList.prototype.remove = function (eventName, eventHandler) {
			var th = this.handlers, h = th[eventName], i;
			if (th.hasOwnProperty(eventName)) {
				if (asc_typeOf(h) !== "array" || asc_typeOf(eventHandler) !== "function") {
					delete th[eventName];
					return true;
				}
				for (i = h.length - 1; i >= 0; i -= 1) {
					if (h[i] === eventHandler) {
						delete h[i];
						return true;
					}
				}
			}
			return false;
		};

		//---------------------------------------------------------export---------------------------------------------------
		window['AscCommonExcel'] = window['AscCommonExcel'] || {};
		AscCommonExcel.asc_CHandlersList = asc_CHandlersList;
	}
)(window);
/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(function (window, undefined) {
		/*
		 * Import
		 * -----------------------------------------------------------------------------
		 */
		var asc_applyFunction	= AscCommonExcel.applyFunction;
		var asc_Range			= Asc.Range;

		var c_oAscLockTypes = AscCommon.c_oAscLockTypes;

		var c_oAscRecalcIndexTypes = AscCommonExcel.c_oAscRecalcIndexTypes;
		var c_oAscLockTypeElemSubType = AscCommonExcel.c_oAscLockTypeElemSubType;
		var c_oAscLockTypeElem = AscCommonExcel.c_oAscLockTypeElem;

		/**
		 * Отвечает за совместное редактирование
		 * -----------------------------------------------------------------------------
		 *
		 * @constructor
		 * @memberOf AscCommonExcel
		 */
		function CCollaborativeEditing (handlers, isViewerMode) {
			if ( !(this instanceof CCollaborativeEditing) ) {
				return new CCollaborativeEditing ();
			}

			this.m_nUseType					= 1;  // 1 - 1 клиент и мы сохраняем историю, -1 - несколько клиентов, 0 - переход из -1 в 1

			this.handlers					= new AscCommonExcel.asc_CHandlersList(handlers);
			this.m_bIsViewerMode			= !!isViewerMode; // Режим Viewer-а
			this.m_bGlobalLock				= false; // Глобальный lock
			this.m_bGlobalLockEditCell		= false; // Глобальный lock (для редактирования ячейки) - отключаем смену select-а, но разрешаем сразу вводить
			this.m_arrCheckLocks			= [];    // Массив для проверки залоченности объектов, которые мы собираемся изменять

			this.m_arrNeedUnlock			= []; // Массив со списком залоченных объектов(которые были залочены другими пользователями)
			this.m_arrNeedUnlock2			= []; // Массив со списком залоченных объектов(которые были залочены на данном клиенте)

			this.m_arrChanges				= []; // Массив с изменениями других пользователей

			this.m_oRecalcIndexColumns		= {};
			this.m_oRecalcIndexRows			= {};

			this.m_oInsertColumns			= {}; // Массив листов с массивами списков добавленных колонок
			this.m_oInsertRows				= {}; // Массив листов с массивами списков добавленных строк

      this.m_bFast  = false;

			this.init();

			return this;
		}

		CCollaborativeEditing.prototype.init = function () {
		};

		// Очищаем индексы пересчета (при открытии это необходимо)
		CCollaborativeEditing.prototype.clearRecalcIndex = function () {
			this.m_oRecalcIndexColumns = {};
			this.m_oRecalcIndexRows = {};
		};

		// Начало совместного редактирования
		CCollaborativeEditing.prototype.startCollaborationEditing = function() {
			this.m_nUseType = -1;
		};

		// Временное окончание совместного редактирования
		CCollaborativeEditing.prototype.endCollaborationEditing = function() {
			if (this.m_nUseType <= 0)
				this.m_nUseType = 0;
		};

		// Выставление режима view
		CCollaborativeEditing.prototype.setViewerMode = function (isViewerMode) {
			this.m_bIsViewerMode = isViewerMode;
		};

  CCollaborativeEditing.prototype.setFast = function (bFast) {
    return this.m_bFast = bFast;
  };
  CCollaborativeEditing.prototype.getFast = function () {
    return this.m_bFast;
  };
		CCollaborativeEditing.prototype.Is_SingleUser = function () {
			return !this.getCollaborativeEditing();
		};
		CCollaborativeEditing.prototype.getCollaborativeEditing = function () {
			if (this.m_bIsViewerMode)
				return false;
			return 1 !== this.m_nUseType;
		};

  CCollaborativeEditing.prototype.haveOtherChanges = function () {
    return 0 < this.m_arrChanges.length;
  };

		CCollaborativeEditing.prototype.getOwnLocksLength = function () {
			return this.m_arrNeedUnlock2.length;
		};

		//-----------------------------------------------------------------------------------
		// Функции для проверки залоченности объектов
		//-----------------------------------------------------------------------------------
		CCollaborativeEditing.prototype.getGlobalLock = function () {
			return this.m_bGlobalLock;
		};
		CCollaborativeEditing.prototype.getGlobalLockEditCell = function () {
			return this.m_bGlobalLockEditCell;
		};
		CCollaborativeEditing.prototype.onStartEditCell = function () {
			// Вызывать эту функцию только в случае редактирования ячейки и если мы не одни редактируем!!!
			if (this.getCollaborativeEditing())
				this.m_bGlobalLockEditCell = true;
		};
		CCollaborativeEditing.prototype.onStopEditCell = function () {
			// Вызывать эту функцию только в случае окончания редактирования ячейки!!!
			this.m_bGlobalLockEditCell = false;
		};
		CCollaborativeEditing.prototype.lock = function (arrLocks, callback) {
			var type;
			callback = this._checkCollaborative(callback);

			this.onStartCheckLock();
			for (var i = 0; i < arrLocks.length; ++i) {
				type = this._addCheckLock(arrLocks[i], callback);
				if (c_oAscLockTypes.kLockTypeNone !== type) {
					// Снимаем глобальный лок (для редактирования ячейки)
					this.m_bGlobalLockEditCell = false;
					return c_oAscLockTypes.kLockTypeMine === type;
				}
			}
			this.onEndCheckLock(callback);
			return true;
		};
		CCollaborativeEditing.prototype._checkCollaborative = function (callback) {
			if (false === this.getCollaborativeEditing()) {
				// Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование
				AscCommonExcel.applyFunction(callback, true);
				callback = undefined;
			}
			return callback;
		};
		CCollaborativeEditing.prototype._addCheckLock = function (lockInfo, callback) {
			if (false !== this.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, false)) {
				// Редактируем сами
				AscCommonExcel.applyFunction(callback, true);
				return c_oAscLockTypes.kLockTypeMine;
			} else if (false !== this.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false)) {
				// Уже ячейку кто-то редактирует
				AscCommonExcel.applyFunction(callback, false);
				return c_oAscLockTypes.kLockTypeOther;
			}

			this.m_arrCheckLocks.push(lockInfo);
			return c_oAscLockTypes.kLockTypeNone;
		};
		CCollaborativeEditing.prototype.onStartCheckLock = function () {
			this.m_arrCheckLocks.length = 0;
		};
		CCollaborativeEditing.prototype.addCheckLock = function (oItem) {
			this.m_arrCheckLocks.push (oItem);
		};
		CCollaborativeEditing.prototype.onEndCheckLock = function (callback) {
			var t = this;
			if (this.m_arrCheckLocks.length > 0) {
				// Отправляем запрос на сервер со списком элементов
				this.handlers.trigger("askLock", this.m_arrCheckLocks, function (result) {t.onCallbackAskLock (result, callback);});

				if (undefined !== callback) {
					// Ставим глобальный лок (только если мы не одни и ждем ответа!)
					this.m_bGlobalLock = true;
				}
			}
			else {
				asc_applyFunction(callback, true);

				// Снимаем глобальный лок (для редактирования ячейки)
				this.m_bGlobalLockEditCell = false;
			}
		};

		CCollaborativeEditing.prototype.onCallbackAskLock = function(result, callback) {
			// Снимаем глобальный лок
			this.m_bGlobalLock = false;
			// Снимаем глобальный лок (для редактирования ячейки)
			this.m_bGlobalLockEditCell = false;

			if (result["lock"]) {
				// Пробегаемся по массиву и проставляем, что залочено нами
				var count = this.m_arrCheckLocks.length;
				for (var i = 0; i < count; ++i) {
					var oItem = this.m_arrCheckLocks[i];

					if (true !== oItem && false !== oItem) // сравниваем по значению и типу обязательно
					{
						var oNewLock = new CLock(oItem);
						oNewLock.setType (c_oAscLockTypes.kLockTypeMine);
						this.addUnlock2 (oNewLock);
					}
				}

				asc_applyFunction(callback, true);
			} else if (result["error"]) {
				asc_applyFunction(callback, false);
			}
		};
		CCollaborativeEditing.prototype.addUnlock = function (LockClass) {
			this.m_arrNeedUnlock.push (LockClass);
		};
		CCollaborativeEditing.prototype.addUnlock2 = function (Lock) {
			this.m_arrNeedUnlock2.push (Lock);
			this.handlers.trigger("updateDocumentCanSave");
		};

		CCollaborativeEditing.prototype.removeUnlock = function (Lock) {
			for (var i = 0; i < this.m_arrNeedUnlock.length; ++i)
				if (Lock.Element["guid"] === this.m_arrNeedUnlock[i].Element["guid"]) {
					this.m_arrNeedUnlock.splice(i, 1);
					return true;
				}
			return false;
		};

		CCollaborativeEditing.prototype.addChanges = function (oChanges) {
			this.m_arrChanges.push (oChanges);
		};

		// Возвращает - нужно ли отправлять end action
		CCollaborativeEditing.prototype.applyChanges = function () {
			var t = this;
			var length = this.m_arrChanges.length;
			// Принимаем изменения
			if (0 < length) {
				//splice to prevent double apply other changes in case of load fonts
				var changes = t.m_arrChanges.splice(0, length);
				this.handlers.trigger("applyChanges", changes, function () {
					t.handlers.trigger("updateAfterApplyChanges");
				});

				return false;
			}

			return true;
		};

		CCollaborativeEditing.prototype.sendChanges = function (IsUserSave, isAfterAskSave) {
			// Когда не совместное редактирование чистить ничего не нужно, но отправлять нужно.
			var bIsCollaborative = this.getCollaborativeEditing();

			var bCheckRedraw = false, bRedrawGraphicObjects = false, bUnlockDefName = false;
			var oLock = null;
			if (bIsCollaborative) {
				if (0 < this.m_arrNeedUnlock.length || 0 < this.m_arrNeedUnlock2.length) {
					bCheckRedraw = true;
					this.handlers.trigger("cleanSelection");
				}

				// Очищаем свои изменения
				while (0 < this.m_arrNeedUnlock2.length) {
					oLock = this.m_arrNeedUnlock2.shift();
					oLock.setType(c_oAscLockTypes.kLockTypeNone, false);

					var drawing = AscCommon.g_oTableId.Get_ById(oLock.Element["rangeOrObjectId"]);
					if(drawing && drawing.lockType !== c_oAscLockTypes.kLockTypeNone) {
						drawing.lockType = c_oAscLockTypes.kLockTypeNone;
						bRedrawGraphicObjects = true;
					}
					if(!bUnlockDefName){
						bUnlockDefName = this.handlers.trigger("checkDefNameLock", oLock);
					}

					this.handlers.trigger("releaseLocks", oLock.Element["guid"]);
				}

				// Очищаем примененные чужие изменения
				var nIndex = 0;
				var nCount = this.m_arrNeedUnlock.length;
				for (;nIndex < nCount; ++nIndex) {
					oLock = this.m_arrNeedUnlock[nIndex];
					if (c_oAscLockTypes.kLockTypeOther2 === oLock.getType()) {
						if (!this.handlers.trigger("checkCommentRemoveLock", oLock.Element)) {
							drawing = AscCommon.g_oTableId.Get_ById(oLock.Element["rangeOrObjectId"]);
							if(drawing && drawing.lockType !== c_oAscLockTypes.kLockTypeNone) {
								drawing.lockType = c_oAscLockTypes.kLockTypeNone;
								bRedrawGraphicObjects = true;
							}
							if(!bUnlockDefName){
								bUnlockDefName = this.handlers.trigger("checkDefNameLock", oLock);
							}
						}

						this.m_arrNeedUnlock.splice(nIndex, 1);
						--nIndex;
						--nCount;
					}
				}
			}

			// Отправляем на сервер изменения
			this.handlers.trigger("sendChanges", this.getRecalcIndexSave(this.m_oRecalcIndexColumns), this.getRecalcIndexSave(this.m_oRecalcIndexRows), isAfterAskSave);

			if (bIsCollaborative) {
				// Пересчитываем lock-и от чужих пользователей
				this._recalcLockArrayOthers();

				// Очищаем свои изменения (удаляем массив добавленных строк/столбцов)
				delete this.m_oInsertColumns;
				delete this.m_oInsertRows;
				this.m_oInsertColumns = {};
				this.m_oInsertRows = {};
				// Очищаем свои пересчетные индексы
				this.clearRecalcIndex();

				// Чистим Undo/Redo
				AscCommon.History.Clear();

				// Перерисовываем
				if (bCheckRedraw) {
					this.handlers.trigger("drawSelection");
					this.handlers.trigger("drawFrozenPaneLines");
					this.handlers.trigger("updateAllSheetsLock");
					this.handlers.trigger("showComments");
				}

				if (bCheckRedraw || bRedrawGraphicObjects)
					this.handlers.trigger("showDrawingObjects");

//                if(bUnlockDefName){
                    this.handlers.trigger("unlockDefName");
//                }

				this.handlers.trigger("updateAllLayoutsLock");

				if (0 === this.m_nUseType)
					this.m_nUseType = 1;
			} else {
				// Обновляем точку последнего сохранения в истории
				AscCommon.History.Reset_SavedIndex(IsUserSave);
			}
		};

		CCollaborativeEditing.prototype.getRecalcIndexSave = function (oRecalcIndex) {
			var bHasIndex = false;
			var result = {};
			var element = null;
			for (var sheetId in oRecalcIndex) {
				if (!oRecalcIndex.hasOwnProperty(sheetId))
					continue;
				result[sheetId] = {"_arrElements": []};
				for (var i = 0, length = oRecalcIndex[sheetId]._arrElements.length; i < length; ++i) {
					bHasIndex = true;
					element = oRecalcIndex[sheetId]._arrElements[i];
					result[sheetId]["_arrElements"].push({"_recalcType" : element._recalcType,
						"_position" : element._position, "_count" : element._count,
						"m_bIsSaveIndex" : element.m_bIsSaveIndex});
				}
			}

			return bHasIndex ? result : null;
		};

		CCollaborativeEditing.prototype.S4 = function () {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		};
		CCollaborativeEditing.prototype.createGUID = function () {
			return (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
		};

		CCollaborativeEditing.prototype.getLockInfo = function (typeElem, subType, sheetId, info) {
			var oLockInfo = new AscCommonExcel.asc_CLockInfo();
			oLockInfo["sheetId"] = sheetId;
			oLockInfo["type"] = typeElem;
			oLockInfo["subType"] = subType;
			oLockInfo["guid"] = this.createGUID();
			oLockInfo["rangeOrObjectId"] = info;
			return oLockInfo;
		};

		CCollaborativeEditing.prototype.getLockByElem = function (element, type) {
			var arrayElements = (c_oAscLockTypes.kLockTypeMine === type) ? this.m_arrNeedUnlock2 : this.m_arrNeedUnlock;
			for (var i = 0; i < arrayElements.length; ++i)
				if (element["guid"] === arrayElements[i].Element["guid"])
					return arrayElements[i];
			return null;
		};

		/**
		 * Проверка lock для элемента
		 * @param {asc_CLockInfo} element  элемент для проверки lock
		 * @param {c_oAscLockTypes} type сами(kLockTypeMine) или кто-то другой
		 * @param {Boolean} bCheckOnlyLockAll проверять только lock для свойств всего листа (либо только проверять удален ли лист, а не просто залочен)
		 */
		CCollaborativeEditing.prototype.getLockIntersection = function (element, type, bCheckOnlyLockAll) {
			var arrayElements = (c_oAscLockTypes.kLockTypeMine === type) ? this.m_arrNeedUnlock2 : this.m_arrNeedUnlock;
			var oUnlockElement = null, rangeTmp1, rangeTmp2;
			for (var i = 0; i < arrayElements.length; ++i) {
				oUnlockElement = arrayElements[i].Element;
				if (c_oAscLockTypeElem.Sheet === element["type"] && element["type"] === oUnlockElement["type"]) {
					// Проверка только на удаление листа (если проверка для себя, то выходим не сразу, т.к. нужно проверить lock от других элементов)
					if ((c_oAscLockTypes.kLockTypeMine !== type && false === bCheckOnlyLockAll) ||
						element["sheetId"] === oUnlockElement["sheetId"]) {
						// Если кто-то залочил sheet, то больше никто не может лочить sheet-ы (иначе можно удалить все листы)
						return arrayElements[i];
					}
				}
				if (element["sheetId"] !== oUnlockElement["sheetId"])
					continue;

				if (null !== element["subType"] && null !== oUnlockElement["subType"])
					return arrayElements[i];

				// Не учитываем lock от ChangeProperties (только если это не lock листа)
				if (true === bCheckOnlyLockAll ||
					(c_oAscLockTypeElemSubType.ChangeProperties === oUnlockElement["subType"]
						&& c_oAscLockTypeElem.Sheet !== element["type"]))
					continue;

				if (element["type"] === oUnlockElement["type"]) {
					if (element["type"] === c_oAscLockTypeElem.Object) {
						if (element["rangeOrObjectId"] === oUnlockElement["rangeOrObjectId"])
							return arrayElements[i];
					} else if (element["type"] === c_oAscLockTypeElem.Range) {
						// Не учитываем lock от Insert
						if (c_oAscLockTypes.kLockTypeMine === type || c_oAscLockTypeElemSubType.InsertRows === oUnlockElement["subType"] || c_oAscLockTypeElemSubType.InsertColumns === oUnlockElement["subType"])
							continue;
						rangeTmp1 = oUnlockElement["rangeOrObjectId"];
						rangeTmp2 = element["rangeOrObjectId"];
						if (rangeTmp2["c1"] > rangeTmp1["c2"] || rangeTmp2["c2"] < rangeTmp1["c1"] || rangeTmp2["r1"] > rangeTmp1["r2"] || rangeTmp2["r2"] < rangeTmp1["r1"])
							continue;
						return arrayElements[i];
					}
				} else if (oUnlockElement["type"] === c_oAscLockTypeElem.Sheet ||
					(element["type"] === c_oAscLockTypeElem.Sheet && c_oAscLockTypes.kLockTypeMine !== type)) {
					// Если кто-то уже залочил лист или мы пытаемся сами залочить и проверяем на чужие lock
					return arrayElements[i];
				}
			}
			return false;
		};

		CCollaborativeEditing.prototype.getLockElem = function (typeElem, type, sheetId) {
			var arrayElements = (c_oAscLockTypes.kLockTypeMine === type) ? this.m_arrNeedUnlock2 : this.m_arrNeedUnlock;
			var count = arrayElements.length;
			var element = null, oRangeOrObjectId = null;
			var result = [];
			var c1, c2, r1, r2;

			if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId)) {
				this.m_oRecalcIndexColumns[sheetId] = new CRecalcIndex();
			}
			if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId)) {
				this.m_oRecalcIndexRows[sheetId] = new CRecalcIndex();
			}

			for (var i = 0; i < count; ++i) {
				element = arrayElements[i].Element;
				if (element["sheetId"] !== sheetId || element["type"] !== typeElem)
					continue;

				// Отображать залоченность удаленных текущим пользователем строк/столбцов не нужно (уже нечего отображать)
				if (c_oAscLockTypes.kLockTypeMine === type && c_oAscLockTypeElem.Range === typeElem &&
					(c_oAscLockTypeElemSubType.DeleteColumns === element["subType"] ||
						c_oAscLockTypeElemSubType.DeleteRows === element["subType"]))
					continue;
				// Отображать залоченность добавленных другим пользователем строк/столбцов не нужно (еще нечего отображать)
				if (c_oAscLockTypeElem.Range === typeElem &&
					(c_oAscLockTypeElemSubType.InsertColumns === element["subType"] ||
						c_oAscLockTypeElemSubType.InsertRows === element["subType"]))
					continue;
				// Отображать lock-диапазон для lockAll(всего листа) не нужно
				if (c_oAscLockTypeElemSubType.ChangeProperties === element["subType"])
					continue;

				oRangeOrObjectId = element["rangeOrObjectId"];
				// Для диапазона нужно сделать пересчет с учетом удаленных или добавленных строк/столбцов
				if (c_oAscLockTypeElem.Range === typeElem) {
					// Пересчитывать для удаленных строк/столбцов у другого пользователя не нужно
					if (c_oAscLockTypes.kLockTypeMine !== type && c_oAscLockTypeElem.Range === typeElem &&
						(c_oAscLockTypeElemSubType.DeleteColumns === element["subType"] ||
							c_oAscLockTypeElemSubType.DeleteRows === element["subType"])) {
						c1 = oRangeOrObjectId["c1"];
						c2 = oRangeOrObjectId["c2"];
						r1 = oRangeOrObjectId["r1"];
						r2 = oRangeOrObjectId["r2"];
					} else {
						c1 = this.m_oRecalcIndexColumns[sheetId].getLockOther(oRangeOrObjectId["c1"], type);
						c2 = this.m_oRecalcIndexColumns[sheetId].getLockOther(oRangeOrObjectId["c2"], type);
						r1 = this.m_oRecalcIndexRows[sheetId].getLockOther(oRangeOrObjectId["r1"], type);
						r2 = this.m_oRecalcIndexRows[sheetId].getLockOther(oRangeOrObjectId["r2"], type);
					}
					if (null === c1 || null === c2 || null === r1 || null === r2)
						continue;

					oRangeOrObjectId = new asc_Range(c1, r1, c2, r2);
				}

				result.push(oRangeOrObjectId);
			}

			return result;
		};

		CCollaborativeEditing.prototype.getLockCellsMe = function (sheetId) {
			return this.getLockElem(c_oAscLockTypeElem.Range, c_oAscLockTypes.kLockTypeMine, sheetId);
		};
		CCollaborativeEditing.prototype.getLockCellsOther = function (sheetId) {
			return this.getLockElem(c_oAscLockTypeElem.Range, c_oAscLockTypes.kLockTypeOther, sheetId);
		};
		CCollaborativeEditing.prototype.getLockObjectsMe = function (sheetId) {
			return this.getLockElem(c_oAscLockTypeElem.Object, c_oAscLockTypes.kLockTypeMine, sheetId);
		};
		CCollaborativeEditing.prototype.getLockObjectsOther = function (sheetId) {
			return this.getLockElem(c_oAscLockTypeElem.Object, c_oAscLockTypes.kLockTypeOther, sheetId);
		};
		/**
		 * Проверка lock для всего листа
		 * @param {Number} sheetId  элемент для проверки lock
		 * @return {Asc.c_oAscMouseMoveLockedObjectType} oLockedObjectType
		 */
		CCollaborativeEditing.prototype.isLockAllOther = function (sheetId) {
			var arrayElements = this.m_arrNeedUnlock;
			var count = arrayElements.length;
			var element = null;
			var oLockedObjectType = Asc.c_oAscMouseMoveLockedObjectType.None;

			for (var i = 0; i < count; ++i) {
				element = arrayElements[i].Element;
				if (element["sheetId"] === sheetId) {
					if (element["type"] === c_oAscLockTypeElem.Sheet) {
						oLockedObjectType = Asc.c_oAscMouseMoveLockedObjectType.Sheet;
						break;
					} else if (element["type"] === c_oAscLockTypeElem.Range && null !== element["subType"])
						oLockedObjectType = Asc.c_oAscMouseMoveLockedObjectType.TableProperties;
				}
			}
			return oLockedObjectType;
		};

		CCollaborativeEditing.prototype._recalcLockArray = function (typeLock, oRecalcIndexColumns, oRecalcIndexRows) {
			var arrayElements = (c_oAscLockTypes.kLockTypeMine === typeLock) ? this.m_arrNeedUnlock2 : this.m_arrNeedUnlock;
			var count = arrayElements.length;
			var element = null, oRangeOrObjectId = null;
			var i;
			var sheetId = -1;

			for (i = 0; i < count; ++i) {
				element = arrayElements[i].Element;
				// Для удаления пересчитывать индексы не нужно
				if (c_oAscLockTypeElem.Range !== element["type"] ||
					c_oAscLockTypeElemSubType.InsertColumns === element["subType"] ||
					c_oAscLockTypeElemSubType.InsertRows === element["subType"] ||
					c_oAscLockTypeElemSubType.DeleteColumns === element["subType"] ||
					c_oAscLockTypeElemSubType.DeleteRows === element["subType"])
					continue;
				sheetId = element["sheetId"];

				oRangeOrObjectId = element["rangeOrObjectId"];

				if (oRecalcIndexColumns && oRecalcIndexColumns.hasOwnProperty(sheetId)) {
					// Пересчет колонок
					oRangeOrObjectId["c1"] = oRecalcIndexColumns[sheetId].getLockMe(oRangeOrObjectId["c1"]);
					oRangeOrObjectId["c2"] = oRecalcIndexColumns[sheetId].getLockMe(oRangeOrObjectId["c2"]);
				}
				if (oRecalcIndexRows && oRecalcIndexRows.hasOwnProperty(sheetId)) {
					// Пересчет строк
					oRangeOrObjectId["r1"] = oRecalcIndexRows[sheetId].getLockMe(oRangeOrObjectId["r1"]);
					oRangeOrObjectId["r2"] = oRecalcIndexRows[sheetId].getLockMe(oRangeOrObjectId["r2"]);
				}
			}
		};
		// Пересчет только для чужих Lock при сохранении на клиенте, который добавлял/удалял строки или столбцы
		CCollaborativeEditing.prototype._recalcLockArrayOthers = function () {
			var typeLock = c_oAscLockTypes.kLockTypeOther;
			var arrayElements = (c_oAscLockTypes.kLockTypeMine === typeLock) ? this.m_arrNeedUnlock2 : this.m_arrNeedUnlock;
			var count = arrayElements.length;
			var element = null, oRangeOrObjectId = null;
			var i;
			var sheetId = -1;

			for (i = 0; i < count; ++i) {
				element = arrayElements[i].Element;
				if (c_oAscLockTypeElem.Range !== element["type"] ||
					c_oAscLockTypeElemSubType.InsertColumns === element["subType"] ||
					c_oAscLockTypeElemSubType.InsertRows === element["subType"])
					continue;
				sheetId = element["sheetId"];

				oRangeOrObjectId = element["rangeOrObjectId"];

				if (this.m_oRecalcIndexColumns.hasOwnProperty(sheetId)) {
					// Пересчет колонок
					oRangeOrObjectId["c1"] = this.m_oRecalcIndexColumns[sheetId].getLockOther(oRangeOrObjectId["c1"]);
					oRangeOrObjectId["c2"] = this.m_oRecalcIndexColumns[sheetId].getLockOther(oRangeOrObjectId["c2"]);
				}
				if (this.m_oRecalcIndexRows.hasOwnProperty(sheetId)) {
					// Пересчет строк
					oRangeOrObjectId["r1"] = this.m_oRecalcIndexRows[sheetId].getLockOther(oRangeOrObjectId["r1"]);
					oRangeOrObjectId["r2"] = this.m_oRecalcIndexRows[sheetId].getLockOther(oRangeOrObjectId["r2"]);
				}
			}
		};

		CCollaborativeEditing.prototype.addRecalcIndex = function (type, oRecalcIndex) {
			if (null == oRecalcIndex)
				return null;
			var nIndex = 0;
			var nRecalcType = c_oAscRecalcIndexTypes.RecalcIndexAdd;
			var oRecalcIndexElement = null;
			var oRecalcIndexResult = {};

			var oRecalcIndexTmp = ("0" === type) ? this.m_oRecalcIndexColumns : this.m_oRecalcIndexRows;
			for (var sheetId in oRecalcIndex) {
				if (oRecalcIndex.hasOwnProperty(sheetId)) {
					if (!oRecalcIndexTmp.hasOwnProperty(sheetId)) {
						oRecalcIndexTmp[sheetId] = new CRecalcIndex();
					}
					if (!oRecalcIndexResult.hasOwnProperty(sheetId)) {
						oRecalcIndexResult[sheetId] = new CRecalcIndex();
					}
					for (; nIndex < oRecalcIndex[sheetId]["_arrElements"].length; ++nIndex) {
						oRecalcIndexElement = oRecalcIndex[sheetId]["_arrElements"][nIndex];
						if (true === oRecalcIndexElement["m_bIsSaveIndex"])
							continue;
						nRecalcType = (c_oAscRecalcIndexTypes.RecalcIndexAdd === oRecalcIndexElement["_recalcType"]) ?
							c_oAscRecalcIndexTypes.RecalcIndexRemove : c_oAscRecalcIndexTypes.RecalcIndexAdd;
						oRecalcIndexTmp[sheetId].add(nRecalcType, oRecalcIndexElement["_position"],
							oRecalcIndexElement["_count"], /*bIsSaveIndex*/true);
						// Дублируем для возврата результата (нам нужно пересчитать только по последнему индексу
						oRecalcIndexResult[sheetId].add(nRecalcType, oRecalcIndexElement["_position"],
							oRecalcIndexElement["_count"], /*bIsSaveIndex*/true);
					}
				}
			}

			return oRecalcIndexResult;
		};

		// Undo для добавления/удаления столбцов
		CCollaborativeEditing.prototype.undoCols = function (sheetId, count) {
      if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId))
        return;
      this.m_oRecalcIndexColumns[sheetId].remove(count);
		};
		// Undo для добавления/удаления строк
		CCollaborativeEditing.prototype.undoRows = function (sheetId, count) {
      if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId))
        return;
      this.m_oRecalcIndexRows[sheetId].remove(count);
		};

		CCollaborativeEditing.prototype.removeCols = function (sheetId, position, count) {
      if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId)) {
        this.m_oRecalcIndexColumns[sheetId] = new CRecalcIndex();
      }
      this.m_oRecalcIndexColumns[sheetId].add(c_oAscRecalcIndexTypes.RecalcIndexRemove, position,
        count, /*bIsSaveIndex*/false);
		};
		CCollaborativeEditing.prototype.addCols = function (sheetId, position, count) {
      if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId)) {
        this.m_oRecalcIndexColumns[sheetId] = new CRecalcIndex();
      }
      this.m_oRecalcIndexColumns[sheetId].add(c_oAscRecalcIndexTypes.RecalcIndexAdd, position,
        count, /*bIsSaveIndex*/false);
		};
		CCollaborativeEditing.prototype.removeRows = function (sheetId, position, count) {
      if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId)) {
        this.m_oRecalcIndexRows[sheetId] = new CRecalcIndex();
      }
      this.m_oRecalcIndexRows[sheetId].add(c_oAscRecalcIndexTypes.RecalcIndexRemove, position,
        count, /*bIsSaveIndex*/false);
		};
		CCollaborativeEditing.prototype.addRows = function (sheetId, position, count) {
      if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId)) {
        this.m_oRecalcIndexRows[sheetId] = new CRecalcIndex();
      }
      this.m_oRecalcIndexRows[sheetId].add(c_oAscRecalcIndexTypes.RecalcIndexAdd, position,
        count, /*bIsSaveIndex*/false);
		};
		CCollaborativeEditing.prototype.addColsRange = function (sheetId, range) {
			if (!this.m_oInsertColumns.hasOwnProperty(sheetId)) {
				this.m_oInsertColumns[sheetId] = [];
			}
			var arrInsertColumns = this.m_oInsertColumns[sheetId];
			// Перед добавлением нужно передвинуть имеющиеся
			var countCols = range.c2 - range.c1 + 1;
			var isAddNewRange = true;
			for (var i = 0; i < arrInsertColumns.length; ++i) {
				if (arrInsertColumns[i].c1 > range.c1) {
					arrInsertColumns[i].c1 += countCols;
					arrInsertColumns[i].c2 += countCols;
				} else if (arrInsertColumns[i].c1 <= range.c1 && arrInsertColumns[i].c2 >= range.c1) {
					arrInsertColumns[i].c2 += countCols;
					isAddNewRange = false;
				}
			}
			if (isAddNewRange)
				arrInsertColumns.push(range);
		};
		CCollaborativeEditing.prototype.addRowsRange = function (sheetId, range) {
			if (!this.m_oInsertRows.hasOwnProperty(sheetId)) {
				this.m_oInsertRows[sheetId] = [];
			}
			var arrInsertRows = this.m_oInsertRows[sheetId];
			// Перед добавлением нужно передвинуть имеющиеся
			var countRows = range.r2 - range.r1 + 1;
			var isAddNewRange = true;
			for (var i = 0; i < arrInsertRows.length; ++i) {
				if (arrInsertRows[i].r1 > range.r1) {
					arrInsertRows[i].r1 += countRows;
					arrInsertRows[i].r2 += countRows;
				} else if (arrInsertRows[i].r1 <= range.r1 && arrInsertRows[i].r2 >= range.r1) {
					arrInsertRows[i].r2 += countRows;
					isAddNewRange = false;
				}
			}
			if (isAddNewRange)
				arrInsertRows.push(range);
		};
		CCollaborativeEditing.prototype.removeColsRange = function (sheetId, range) {
			if (!this.m_oInsertColumns.hasOwnProperty(sheetId))
				return;
			var arrInsertColumns = this.m_oInsertColumns[sheetId];
			// Нужно убрать те колонки, которые входят в диапазон
			var countCols = range.c2 - range.c1 + 1;
			for (var i = 0; i < arrInsertColumns.length; ++i) {
				if (arrInsertColumns[i].c1 > range.c2) {
					// Справа от удаляемого диапазона
					arrInsertColumns[i].c1 -= countCols;
					arrInsertColumns[i].c2 -= countCols;
				} else if (arrInsertColumns[i].c1 >= range.c1 && arrInsertColumns[i].c2 <= range.c2) {
					// Полностью включение в удаляемый диапазон
					arrInsertColumns.splice(i, 1);
					i -= 1;
				} else if (arrInsertColumns[i].c1 >= range.c1 && arrInsertColumns[i].c1 <= range.c2 && arrInsertColumns[i].c2 > range.c2) {
					// Частичное включение начала диапазона
					arrInsertColumns[i].c1 = range.c2 + 1;
					arrInsertColumns[i].c1 -= countCols;
					arrInsertColumns[i].c2 -= countCols;
				} else if (arrInsertColumns[i].c1 < range.c1 && arrInsertColumns[i].c2 >= range.c1 && arrInsertColumns[i].c2 <= range.c2) {
					// Частичное включение окончания диапазона
					arrInsertColumns[i].c2 = range.c1 - 1;
				} else if (arrInsertColumns[i].c1 < range.c1 && arrInsertColumns[i].c2 > range.c2) {
					// Удаляемый диапазон внутри нашего диапазона
					arrInsertColumns[i].c2 -= countCols;
				}
			}
		};
		CCollaborativeEditing.prototype.removeRowsRange = function (sheetId, range) {
			if (!this.m_oInsertRows.hasOwnProperty(sheetId))
				return;
			var arrInsertRows = this.m_oInsertRows[sheetId];
			// Нужно убрать те строки, которые входят в диапазон
			var countRows = range.r2 - range.r1 + 1;
			for (var i = 0; i < arrInsertRows.length; ++i) {
				if (arrInsertRows[i].r1 > range.r2) {
					// Снизу от удаляемого диапазона
					arrInsertRows[i].r1 -= countRows;
					arrInsertRows[i].r2 -= countRows;
				} else if (arrInsertRows[i].r1 >= range.r1 && arrInsertRows[i].r2 <= range.r2) {
					// Полностью включение в удаляемый диапазон
					arrInsertRows.splice(i, 1);
					i -= 1;
				} else if (arrInsertRows[i].r1 >= range.r1 && arrInsertRows[i].r1 <= range.r2 && arrInsertRows[i].r2 > range.r2) {
					// Частичное включение начала диапазона
					arrInsertRows[i].r1 = range.r2 + 1;
					arrInsertRows[i].r1 -= countRows;
					arrInsertRows[i].r2 -= countRows;
				} else if (arrInsertRows[i].r1 < range.r1 && arrInsertRows[i].r2 >= range.r1 && arrInsertRows[i].r2 <= range.r2) {
					// Частичное включение окончания диапазона
					arrInsertRows[i].r2 = range.r1 - 1;
				} else if (arrInsertRows[i].r1 < range.r1 && arrInsertRows[i].r2 > range.r2) {
					// Удаляемый диапазон внутри нашего диапазона
					arrInsertRows[i].r2 -= countRows;
				}
			}
		};
		CCollaborativeEditing.prototype.isIntersectionInCols = function (sheetId, col) {
			if (!this.m_oInsertColumns.hasOwnProperty(sheetId))
				return false;
			var arrInsertColumns = this.m_oInsertColumns[sheetId];
			for (var i = 0; i < arrInsertColumns.length; ++i) {
				if (arrInsertColumns[i].c1 <= col && col <= arrInsertColumns[i].c2)
					return true;
			}
			return false;
		};
		CCollaborativeEditing.prototype.isIntersectionInRows = function (sheetId, row) {
			if (!this.m_oInsertRows.hasOwnProperty(sheetId))
				return false;
			var arrInsertRows = this.m_oInsertRows[sheetId];
			for (var i = 0; i < arrInsertRows.length; ++i) {
				if (arrInsertRows[i].r1 <= row && row <= arrInsertRows[i].r2)
					return true;
			}
			return false;
		};
		CCollaborativeEditing.prototype.getArrayInsertColumnsBySheetId = function (sheetId) {
			if (!this.m_oInsertColumns.hasOwnProperty(sheetId))
				return [];

			return this.m_oInsertColumns[sheetId];
		};
		CCollaborativeEditing.prototype.getArrayInsertRowsBySheetId = function (sheetId) {
			if (!this.m_oInsertRows.hasOwnProperty(sheetId))
				return [];

			return this.m_oInsertRows[sheetId];
		};
		CCollaborativeEditing.prototype.getLockMeColumn = function (sheetId, col) {
			if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId))
				return col;
			return this.m_oRecalcIndexColumns[sheetId].getLockMe(col);
		};
		CCollaborativeEditing.prototype.getLockMeRow = function (sheetId, row) {
			if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId))
				return row;
			return this.m_oRecalcIndexRows[sheetId].getLockMe(row);
		};
		// Только когда от других пользователей изменения колонок (для пересчета)
		CCollaborativeEditing.prototype.getLockMeColumn2 = function (sheetId, col) {
			if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId))
				return col;
			return this.m_oRecalcIndexColumns[sheetId].getLockMe2(col);
		};
		// Только когда от других пользователей изменения строк (для пересчета)
		CCollaborativeEditing.prototype.getLockMeRow2 = function (sheetId, row) {
			if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId))
				return row;
			return this.m_oRecalcIndexRows[sheetId].getLockMe2(row);
		};
		// Только для принятия изменений от других пользователей! (для пересчета только в сохранении)
		CCollaborativeEditing.prototype.getLockOtherColumn2 = function (sheetId, col) {
			if (!this.m_oRecalcIndexColumns.hasOwnProperty(sheetId))
				return col;
			return this.m_oRecalcIndexColumns[sheetId].getLockSaveOther(col);
		};
		// Только для принятия изменений от других пользователей! (для пересчета только в сохранении)
		CCollaborativeEditing.prototype.getLockOtherRow2 = function (sheetId, row) {
			if (!this.m_oRecalcIndexRows.hasOwnProperty(sheetId))
				return row;
			return this.m_oRecalcIndexRows[sheetId].getLockSaveOther(row);
		};

		/**
		 * Отвечает за лок в совместном редактировании
		 * -----------------------------------------------------------------------------
		 *
		 * @constructor
		 * @memberOf Asc
		 */
		function CLock(element) {
			this.Type   = c_oAscLockTypes.kLockTypeNone;
			this.UserId = null;
			this.Element = element;

			this.init();

			return this;
		}

		CLock.prototype.init = function () {
		};
		CLock.prototype.getType = function () {
			return this.Type;
		};
		CLock.prototype.setType = function (newType) {
			if (newType === c_oAscLockTypes.kLockTypeNone)
				this.UserId = null;

			this.Type = newType;
		};

		CLock.prototype.Lock = function(bMine) {
			if (c_oAscLockTypes.kLockTypeNone === this.Type)
			{
				if (true === bMine)
					this.Type = c_oAscLockTypes.kLockTypeMine;
				else
					this.Type = c_oAscLockTypes.kLockTypeOther;
			}
		};

		CLock.prototype.setUserId = function(UserId) {
			this.UserId = UserId;
		};

		function CRecalcIndexElement(recalcType, position, bIsSaveIndex) {
			if ( !(this instanceof CRecalcIndexElement) ) {
				return new CRecalcIndexElement (recalcType, position, bIsSaveIndex);
			}

			this._recalcType	= recalcType;		// Тип изменений (удаление или добавление)
			this._position		= position;			// Позиция, в которой произошли изменения
			this._count			= 1;				// Считаем все изменения за простейшие
			this.m_bIsSaveIndex	= !!bIsSaveIndex;	// Это индексы из изменений других пользователей (которые мы еще не применили)

			return this;
		}

		// Пересчет для других
		CRecalcIndexElement.prototype.getLockOther = function (position, type) {
			var inc = (c_oAscRecalcIndexTypes.RecalcIndexAdd === this._recalcType) ? +1 : -1;
			if (position === this._position && c_oAscRecalcIndexTypes.RecalcIndexRemove === this._recalcType &&
				true === this.m_bIsSaveIndex) {
				// Мы еще не применили чужие изменения (поэтому для insert не нужно отрисовывать)
				// RecalcIndexRemove (потому что перевертываем для правильной отработки, от другого пользователя
				// пришло RecalcIndexAdd
				return null;
			} else if (position === this._position &&
				c_oAscRecalcIndexTypes.RecalcIndexRemove === this._recalcType &&
				c_oAscLockTypes.kLockTypeMine === type && false === this.m_bIsSaveIndex) {
				// Для пользователя, который удалил столбец, рисовать залоченные ранее в данном столбце ячейки
				// не нужно
				return null;
			} else if (position < this._position)
				return position;
			else
				return (position + inc);
		};
		// Пересчет для других (только для сохранения)
		CRecalcIndexElement.prototype.getLockSaveOther = function (position, type) {
			if (this.m_bIsSaveIndex)
				return position;

			var inc = (c_oAscRecalcIndexTypes.RecalcIndexAdd === this._recalcType) ? +1 : -1;
			if (position === this._position && c_oAscRecalcIndexTypes.RecalcIndexRemove === this._recalcType &&
				true === this.m_bIsSaveIndex) {
				// Мы еще не применили чужие изменения (поэтому для insert не нужно отрисовывать)
				// RecalcIndexRemove (потому что перевертываем для правильной отработки, от другого пользователя
				// пришло RecalcIndexAdd
				return null;
			} else if (position === this._position &&
				c_oAscRecalcIndexTypes.RecalcIndexRemove === this._recalcType &&
				c_oAscLockTypes.kLockTypeMine === type && false === this.m_bIsSaveIndex) {
				// Для пользователя, который удалил столбец, рисовать залоченные ранее в данном столбце ячейки
				// не нужно
				return null;
			} else if (position < this._position)
				return position;
			else
				return (position + inc);
		};
		// Пересчет для себя
		CRecalcIndexElement.prototype.getLockMe = function (position) {
			var inc = (c_oAscRecalcIndexTypes.RecalcIndexAdd === this._recalcType) ? -1 : +1;
			if (position < this._position)
				return position;
			else
				return (position + inc);
		};
		// Только когда от других пользователей изменения (для пересчета)
		CRecalcIndexElement.prototype.getLockMe2 = function (position) {
			var inc = (c_oAscRecalcIndexTypes.RecalcIndexAdd === this._recalcType) ? -1 : +1;
			if (true !== this.m_bIsSaveIndex || position < this._position)
				return position;
			else
				return (position + inc);
		};

		function CRecalcIndex() {
			if ( !(this instanceof CRecalcIndex) ) {
				return new CRecalcIndex ();
			}

			this._arrElements = [];		// Массив CRecalcIndexElement

			return this;
		}

		CRecalcIndex.prototype.add = function (recalcType, position, count, bIsSaveIndex) {
			for (var i = 0; i < count; ++i)
				this._arrElements.push(new CRecalcIndexElement(recalcType, position, bIsSaveIndex));
		};
		// Удаляет из пересчета, для undo
		CRecalcIndex.prototype.remove = function (count) {
			for (var i = 0; i < count; ++i)
				this._arrElements.pop();
		};
		CRecalcIndex.prototype.clear = function () {
			this._arrElements.length = 0;
		};

		// Пересчет для других
		CRecalcIndex.prototype.getLockOther = function (position, type) {
			var newPosition = position;
			/*var count = this._arrElements.length;
			 for (var i = 0; i < count; ++i) {
			 newPosition = this._arrElements[i].getLockOther(newPosition, type);
			 if (null === newPosition)
			 break;
			 }*/

			var count = this._arrElements.length;
			if (0 >= count)
				return newPosition;
			// Для пересчета, когда добавил сам - обратный порядок
			// Для пересчета, когда добавил кто-то другой - прямой
			var bIsDirect = !this._arrElements[0].m_bIsSaveIndex;
			var i;
			if (bIsDirect) {
				for (i = 0; i < count; ++i) {
					newPosition = this._arrElements[i].getLockOther(newPosition, type);
					if (null === newPosition)
						break;
				}
			} else {
				for (i = count - 1; i >= 0; --i) {
					newPosition = this._arrElements[i].getLockOther(newPosition, type);
					if (null === newPosition)
						break;
				}
			}

			return newPosition;
		};
		// Пересчет для других (только для сохранения)
		CRecalcIndex.prototype.getLockSaveOther = function (position, type) {
			var newPosition = position;
			var count = this._arrElements.length;
			for (var i = 0; i < count; ++i) {
				newPosition = this._arrElements[i].getLockSaveOther(newPosition, type);
				if (null === newPosition)
					break;
			}

			return newPosition;
		};
		// Пересчет для себя
		CRecalcIndex.prototype.getLockMe = function (position) {
			var newPosition = position;
			var count = this._arrElements.length;
			if (0 >= count)
				return newPosition;
			// Для пересчета, когда добавил сам - обратный порядок
			// Для пересчета, когда добавил кто-то другой - прямой
			var bIsDirect = this._arrElements[0].m_bIsSaveIndex;
			var i;
			if (bIsDirect) {
				for (i = 0; i < count; ++i) {
					newPosition = this._arrElements[i].getLockMe(newPosition);
					if (null === newPosition)
						break;
				}
			} else {
				for (i = count - 1; i >= 0; --i) {
					newPosition = this._arrElements[i].getLockMe(newPosition);
					if (null === newPosition)
						break;
				}
			}

			return newPosition;
		};
		// Только когда от других пользователей изменения (для пересчета)
		CRecalcIndex.prototype.getLockMe2 = function (position) {
			var newPosition = position;
			var count = this._arrElements.length;
			if (0 >= count)
				return newPosition;
			// Для пересчета, когда добавил сам - обратный порядок
			// Для пересчета, когда добавил кто-то другой - прямой
			var bIsDirect = this._arrElements[0].m_bIsSaveIndex;
			var i;
			if (bIsDirect) {
				for (i = 0; i < count; ++i) {
					newPosition = this._arrElements[i].getLockMe2(newPosition);
					if (null === newPosition)
						break;
				}
			} else {
				for (i = count - 1; i >= 0; --i) {
					newPosition = this._arrElements[i].getLockMe2(newPosition);
					if (null === newPosition)
						break;
				}
			}

			return newPosition;
		};

		//----------------------------------------------------------export----------------------------------------------------
		window['Asc'] = window['Asc'] || {};
		window['AscCommonExcel'] = window['AscCommonExcel'] || {};
		window['AscCommonExcel'].CLock = CLock;

		window['AscCommonExcel'].CCollaborativeEditing = CCollaborativeEditing;
		window['Asc'].CRecalcIndexElement = CRecalcIndexElement;
		window['Asc'].CRecalcIndex = CRecalcIndex;
	}
)(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
function (window, undefined)
{
	/** @constructor */
	function CDocumentMacros()
	{
		this.Id = "_macrosGlobalId";//AscCommon.g_oIdCounter.Get_NewId();

		this.Lock = new AscCommon.CLock();

		this.Data = "";

		AscCommon.g_oTableId.Add(this, this.Id);
	}
	CDocumentMacros.prototype.SetData = function(sData)
	{
		AscCommon.History.Add(new CChangesDocumentMacrosData(this, this.Data, sData));
		this.Data = sData;
	};
	CDocumentMacros.prototype.GetData = function()
	{
		return this.Data;
	};
	CDocumentMacros.prototype.Get_Id = function()
	{
		return this.Id;
	};
	CDocumentMacros.prototype.CheckLock = function()
	{
		this.Lock.Check(this.Id);
	};
	CDocumentMacros.prototype.Write_ToBinary2 = function(Writer)
	{
		Writer.WriteLong(AscDFH.historyitem_type_DocumentMacros);

		// String2 : Id
		// String2 : Data

		Writer.WriteString2("" + this.Id);
		Writer.WriteString2(this.Data);
	};
	CDocumentMacros.prototype.Read_FromBinary2 = function(Reader)
	{
		// String2 : Id
		// String2 : Data

		this.Id   = Reader.GetString2();
		this.Data = Reader.GetString2();
	};

	CDocumentMacros.prototype.Refresh_RecalcData = function()
	{
	};

	AscDFH.changesFactory[AscDFH.historyitem_DocumentMacros_Data]     = CChangesDocumentMacrosData;
	AscDFH.changesRelationMap[AscDFH.historyitem_DocumentMacros_Data] = [AscDFH.historyitem_DocumentMacros_Data];

	/**
	 * @constructor
	 * @extends {AscDFH.CChangesBaseStringProperty}
	 */
	function CChangesDocumentMacrosData(Class, Old, New)
	{
		AscDFH.CChangesBaseStringProperty.call(this, Class, Old, New);
	}
	CChangesDocumentMacrosData.prototype = Object.create(AscDFH.CChangesBaseStringProperty.prototype);
	CChangesDocumentMacrosData.prototype.constructor = CChangesDocumentMacrosData;
	CChangesDocumentMacrosData.prototype.Type = AscDFH.historyitem_DocumentMacros_Data;
	CChangesDocumentMacrosData.prototype.private_SetValue = function(Value)
	{
		this.Class.Data = Value;
	};

	window['AscCommon'] = window['AscCommon'] || {};
	window["AscCommon"].CDocumentMacros = CDocumentMacros;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(function(window, undefined)
{
	var prot;

	// Import
	var c_oEditorId = AscCommon.c_oEditorId;
	var c_oCloseCode = AscCommon.c_oCloseCode;

	var c_oAscError           = Asc.c_oAscError;
	var c_oAscAsyncAction     = Asc.c_oAscAsyncAction;
	var c_oAscAsyncActionType = Asc.c_oAscAsyncActionType;

	/** @constructor */
	function baseEditorsApi(config, editorId)
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["CreateEditorApi"]();

		this.editorId      = editorId;
		this.isLoadFullApi = false;
		this.openResult    = null;

		this.HtmlElementName = config['id-view'] || '';
		this.HtmlElement     = null;

		this.isMobileVersion = (config['mobile'] === true);
		this.isEmbedVersion = (config['embedded'] === true);

		this.isViewMode = false;
		this.restrictions = Asc.c_oAscRestrictionType.None;

		this.FontLoader  = null;
		this.ImageLoader = null;

		this.LoadedObject        = null;
		this.DocumentType        = 0; // 0 - empty, 1 - test, 2 - document (from json)
		this.DocInfo             = null;
		this.documentId          = undefined;
		this.documentUserId      = undefined;
		this.documentUrl         = "null";
		this.documentUrlChanges  = null;
		this.documentCallbackUrl = undefined;		// Ссылка для отправления информации о документе
		this.documentFormat      = "null";
		this.documentTitle       = "null";
		this.documentFormatSave  = Asc.c_oAscFileType.UNKNOWN;

		this.documentOpenOptions = undefined;		// Опции при открытии (пока только опции для CSV)

		// Тип состояния на данный момент (сохранение, открытие или никакое)
		this.advancedOptionsAction = AscCommon.c_oAscAdvancedOptionsAction.None;
		// Тип скачивания файлы(download или event).нужен для txt, csv. запоминаем на asc_DownloadAs используем asc_setAdvancedOptions
		this.downloadType          = AscCommon.DownloadType.None;
		this.OpenDocumentProgress  = new AscCommon.COpenProgress();
		var sProtocol              = window.location.protocol;
		this.documentOrigin        = ((sProtocol && '' !== sProtocol) ? sProtocol + '//' : '') + window.location.host; // for presentation theme url
		this.documentPathname      = window.location.pathname; // for presentation theme url

		// Переменная отвечает, получили ли мы ответ с сервера совместного редактирования
		this.ServerIdWaitComplete = false;

		// Long action
		this.IsLongActionCurrent       = 0;
		this.LongActionCallbacks       = [];
		this.LongActionCallbacksParams = [];

		// AutoSave
		this.autoSaveGap = 0;					// Интервал автосохранения (0 - означает, что автосохранения нет) в милесекундах
		this.lastSaveTime = null;				// Время последнего сохранения
		this.autoSaveGapFast = 2000;			// Интервал быстрого автосохранения (когда человек один) - 2 сек.
		this.autoSaveGapSlow = 10 * 60 * 1000;	// Интервал медленного автосохранения (когда совместно) - 10 минут
		this.intervalWaitAutoSave = 1000;

		// Unlock document
		this.canUnlockDocument = false;
		this.canUnlockDocument2 = false;		// Дублирующий флаг, только для saveChanges или unLockDocument
		this.canStartCoAuthoring = false;

		this.isDocumentCanSave = false;			// Флаг, говорит о возможности сохранять документ (активна кнопка save или нет)

		// translate manager
		this.translateManager = AscCommon.translateManager.init(config['translate']);

		// Chart
		this.chartPreviewManager   = null;
		this.textArtPreviewManager = null;
		this.shapeElementId        = null;
		// Режим вставки диаграмм в редакторе документов
		this.isChartEditor         = false;
		this.isOpenedChartFrame    = false;

		this.MathMenuLoad          = false;

		// CoAuthoring and Chat
		this.User                   = undefined;
		this.CoAuthoringApi         = new AscCommon.CDocsCoApi();
		this.isCoAuthoringEnable    = true;
		// Массив lock-ов, которые были на открытии документа
		this.arrPreOpenLocksObjects = [];

		// Spell Checking
		this.SpellCheckUrl = '';    // Ссылка сервиса для проверки орфографии

		// Результат получения лицензии
		this.licenseResult       = null;
		// Подключились ли уже к серверу
		this.isOnFirstConnectEnd = false;
		// Получили ли лицензию
		this.isOnLoadLicense     = false;
		// Переменная, которая отвечает, послали ли мы окончание открытия документа
		this.isDocumentLoadComplete = false;
		// Переменная, которая отвечает, послали ли мы окончание открытия документа
		this.isPreOpenLocks = true;
		this.isApplyChangesOnOpenEnabled = true;

		this.canSave    = true;        // Флаг нужен чтобы не происходило сохранение пока не завершится предыдущее сохранение
		this.IsUserSave = false;    // Флаг, контролирующий сохранение было сделано пользователем или нет (по умолчанию - нет)
		this.isForceSaveOnUserSave = false;
        this.forceSaveButtonTimeout = null;
        this.forceSaveButtonContinue = false;
        this.forceSaveTimeoutTimeout = null;
		this.disconnectOnSave = null;
		this.forceSaveUndoRequest = false; // Флаг нужен, чтобы мы знали, что данное сохранение пришло по запросу Undo в совместке

		// Version History
		this.VersionHistory = null;				// Объект, который отвечает за точку в списке версий

		//Флаги для применения свойств через слайдеры
		this.noCreatePoint     = false;
		this.exucuteHistory    = false;
		this.exucuteHistoryEnd = false;

		this.selectSearchingResults = false;

		this.isSendStandartTextures = false;

		this.tmpFocus = null;

		this.fCurCallback = null;

		this.pluginsManager = null;

		this.isLockTargetUpdate = false;

		this.lastWorkTime = 0;

		this.signatures = [];

		this.currentPassword = "";

		this.macros = null;

        this.openFileCryptBinary = null;

        this.copyOutEnabled = (config['copyoutenabled'] !== false);

		//config['watermark_on_draw'] = window.TEST_WATERMARK_STRING;
		this.watermarkDraw =
			config['watermark_on_draw'] ? new AscCommon.CWatermarkOnDraw(config['watermark_on_draw']) : null;

		return this;
	}

	baseEditorsApi.prototype._init                           = function()
	{
		var t            = this;
		//Asc.editor = Asc['editor'] = AscCommon['editor'] = AscCommon.editor = this; // ToDo сделать это!
		this.HtmlElement = document.getElementById(this.HtmlElementName);

		// init OnMessage
		AscCommon.InitOnMessage(function(error, url)
		{
			if (c_oAscError.ID.No !== error)
			{
				t.sendEvent("asc_onError", error, c_oAscError.Level.NoCritical);
			}
			else
			{
				t._addImageUrl([url]);
			}

			t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
		});

		AscCommon.loadSdk(this._editorNameById(), function()
		{
			t.isLoadFullApi = true;

			t._onEndLoadSdk();
			t.onEndLoadDocInfo();
		}, function(err) {
			t.sendEvent("asc_onError", Asc.c_oAscError.ID.LoadingScriptError, c_oAscError.Level.Critical);
		});

		var oldOnError = window.onerror;
		window.onerror = function(errorMsg, url, lineNumber, column, errorObj) {
			var msg = 'Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber + ':' + column +
				' userAgent: ' + (navigator.userAgent || navigator.vendor || window.opera) + ' platform: ' +
				navigator.platform + ' isLoadFullApi: ' + t.isLoadFullApi + ' isDocumentLoadComplete: ' +
				t.isDocumentLoadComplete + ' StackTrace: ' + (errorObj ? errorObj.stack : "");
			t.CoAuthoringApi.sendChangesError(msg);
			//send only first error to reduce number of requests. also following error may be consequences of first
			window.onerror = oldOnError;
			if (oldOnError) {
				return oldOnError.apply(this, arguments);
			} else {
				return false;
			}
		}
	};
	baseEditorsApi.prototype._editorNameById                 = function()
	{
		var res = '';
		switch (this.editorId)
		{
			case c_oEditorId.Word:
				res = 'word';
				break;
			case c_oEditorId.Spreadsheet:
				res = 'cell';
				break;
			case c_oEditorId.Presentation:
				res = 'slide';
				break;
		}
		return res;
	};
	baseEditorsApi.prototype.getEditorId                     = function()
	{
		return this.editorId;
	};
	baseEditorsApi.prototype.asc_GetFontThumbnailsPath       = function()
	{
		return '../Common/Images/';
	};
	baseEditorsApi.prototype.asc_getDocumentName             = function()
	{
		return this.documentTitle;
	};
	baseEditorsApi.prototype.asc_setDocInfo                  = function(oDocInfo)
	{
		var oldInfo = this.DocInfo;
		if (oDocInfo)
		{
			this.DocInfo = oDocInfo;
		}

		if (this.DocInfo)
		{
			this.documentId          = this.DocInfo.get_Id();
			this.documentUserId      = this.DocInfo.get_UserId();
			this.documentUrl         = this.DocInfo.get_Url();
			this.documentTitle       = this.DocInfo.get_Title();
			this.documentFormat      = this.DocInfo.get_Format();
			this.documentCallbackUrl = this.DocInfo.get_CallbackUrl();

			this.documentOpenOptions = this.DocInfo.asc_getOptions();

			this.User = new AscCommon.asc_CUser();
			this.User.setId(this.DocInfo.get_UserId());
			this.User.setUserName(this.DocInfo.get_UserName());
			this.User.setFirstName(this.DocInfo.get_FirstName());
			this.User.setLastName(this.DocInfo.get_LastName());

			//чтобы в versionHistory был один documentId для auth и open
			this.CoAuthoringApi.setDocId(this.documentId);

			if (this.watermarkDraw)
			{
				this.watermarkDraw.CheckParams(this);
			}
		}

		if (AscCommon.chartMode === this.documentUrl)
		{
			this.isChartEditor = true;
            AscCommon.EncryptionWorker.isChartEditor = true;
			this.DocInfo.put_OfflineApp(true);
		}
		else if (AscCommon.offlineMode === this.documentUrl)
		{
			this.DocInfo.put_OfflineApp(true);
		}

		if (undefined !== window["AscDesktopEditor"] && !(this.DocInfo && this.DocInfo.get_OfflineApp()))
		{
			window["AscDesktopEditor"]["SetDocumentName"](this.documentTitle);
		}

        if (!this.isChartEditor && undefined !== window["AscDesktopEditor"] && undefined !== window["AscDesktopEditor"]["CryptoMode"])
        {
            this.DocInfo.put_Encrypted(0 < window["AscDesktopEditor"]["CryptoMode"]);
        }

		if (!oldInfo)
		{
			this.onEndLoadDocInfo();
		}
	};
	baseEditorsApi.prototype.asc_enableKeyEvents             = function(isEnabled, isFromInput)
	{
	};
	// Copy/Past/Cut
	baseEditorsApi.prototype.asc_IsFocus                     = function(bIsNaturalFocus)
	{
		var _ret = false;
		if (this.WordControl.IsFocus)
			_ret = true;
		if (_ret && bIsNaturalFocus && this.WordControl.TextBoxInputFocus)
			_ret = false;
		return _ret;
	};
	baseEditorsApi.prototype.isCopyOutEnabled                = function()
	{
		return this.copyOutEnabled;
	};
	// target pos
	baseEditorsApi.prototype.asc_LockTargetUpdate		     = function(isLock)
	{
		this.isLockTargetUpdate = isLock;
	};
	// Просмотр PDF
	baseEditorsApi.prototype.isPdfViewer                     = function()
	{
		return false;
	};
	// Events
	baseEditorsApi.prototype.sendEvent                       = function()
	{
	};
	baseEditorsApi.prototype.SendOpenProgress                = function()
	{
		this.sendEvent("asc_onOpenDocumentProgress", this.OpenDocumentProgress);
	};
	baseEditorsApi.prototype.sync_InitEditorFonts            = function(gui_fonts)
	{
		if (!this.isViewMode) {
			this.sendEvent("asc_onInitEditorFonts", gui_fonts);
		}
	};
	baseEditorsApi.prototype.sync_StartAction                = function(type, id)
	{
		this.sendEvent('asc_onStartAction', type, id);
		//console.log("asc_onStartAction: type = " + type + " id = " + id);

		if (c_oAscAsyncActionType.BlockInteraction === type)
		{
			this.incrementCounterLongAction();
		}
	};
	baseEditorsApi.prototype.sync_EndAction                  = function(type, id)
	{
		this.sendEvent('asc_onEndAction', type, id);
		//console.log("asc_onEndAction: type = " + type + " id = " + id);

		if (c_oAscAsyncActionType.BlockInteraction === type)
		{
			this.decrementCounterLongAction();
		}
	};
	baseEditorsApi.prototype.sync_TryUndoInFastCollaborative = function()
	{
		this.sendEvent("asc_OnTryUndoInFastCollaborative");
	};
	baseEditorsApi.prototype.asc_setViewMode                 = function()
	{
	};
	baseEditorsApi.prototype.asc_setRestriction              = function(val)
	{
		this.restrictions = val;
	};
	baseEditorsApi.prototype.getViewMode                     = function()
	{
		return this.isViewMode;
	};
	baseEditorsApi.prototype.canEdit                         = function()
	{
		return !this.isViewMode && this.restrictions === Asc.c_oAscRestrictionType.None;
	};
	baseEditorsApi.prototype.isRestrictionForms              = function()
	{
		return (this.restrictions === Asc.c_oAscRestrictionType.OnlyForms);
	};
	baseEditorsApi.prototype.isRestrictionComments           = function()
	{
		return (this.restrictions === Asc.c_oAscRestrictionType.OnlyComments);
	};
	baseEditorsApi.prototype.isRestrictionSignatures         = function()
	{
		return (this.restrictions === Asc.c_oAscRestrictionType.OnlySignatures);
	};
	baseEditorsApi.prototype.isRestrictionView               = function()
	{
		return (this.restrictions === Asc.c_oAscRestrictionType.View);
	};
	baseEditorsApi.prototype.isLongAction                    = function()
	{
		return (0 !== this.IsLongActionCurrent);
	};
	baseEditorsApi.prototype.incrementCounterLongAction      = function()
	{
		++this.IsLongActionCurrent;
	};
	baseEditorsApi.prototype.decrementCounterLongAction      = function()
	{
		this.IsLongActionCurrent--;
		if (this.IsLongActionCurrent < 0)
		{
			this.IsLongActionCurrent = 0;
		}

		if (!this.isLongAction())
		{
			var _length = this.LongActionCallbacks.length;
			for (var i = 0; i < _length; i++)
			{
				this.LongActionCallbacks[i](this.LongActionCallbacksParams[i]);
			}
			this.LongActionCallbacks.splice(0, _length);
			this.LongActionCallbacksParams.splice(0, _length);
		}
	};
	baseEditorsApi.prototype.checkLongActionCallback         = function(_callback, _param)
	{
		if (this.isLongAction())
		{
			this.LongActionCallbacks[this.LongActionCallbacks.length]             = _callback;
			this.LongActionCallbacksParams[this.LongActionCallbacksParams.length] = _param;
			return false;
		}
		else
		{
			return true;
		}
	};
	/**
	 * Функция для загрузчика шрифтов (нужно ли грузить default шрифты). Для Excel всегда возвращаем false
	 * @returns {boolean}
	 */
	baseEditorsApi.prototype.IsNeedDefaultFonts = function()
	{
		var res = false;
		switch (this.editorId)
		{
			case c_oEditorId.Word:
				res = !this.isPdfViewer();
				break;
			case c_oEditorId.Presentation:
				res = true;
				break;
		}
		return res;
	};
	baseEditorsApi.prototype.onPrint                             = function()
	{
		this.sendEvent("asc_onPrint");
	};
	// Open
	baseEditorsApi.prototype.asc_LoadDocument                    = function(versionHistory, isRepeat)
	{
		// Меняем тип состояния (на открытие)
		this.advancedOptionsAction = AscCommon.c_oAscAdvancedOptionsAction.Open;
		var rData                  = null;
		if (!(this.DocInfo && this.DocInfo.get_OfflineApp()))
		{
			rData = {
				"c"             : 'open',
				"id"            : this.documentId,
				"userid"        : this.documentUserId,
				"format"        : this.documentFormat,
				"url"           : this.documentUrl,
				"title"         : this.documentTitle,
				"nobase64"      : true
			};
			if (versionHistory)
			{
				rData["serverVersion"] = versionHistory.serverVersion;
                rData["closeonerror"] = versionHistory.isRequested;
				rData["jwt"] = versionHistory.token;
				//чтобы результат пришел только этому соединению, а не всем кто в документе
				rData["userconnectionid"] = this.CoAuthoringApi.getUserConnectionId();
			}
		}
		if (versionHistory) {
			this.CoAuthoringApi.versionHistory(rData);
		} else {
			this.CoAuthoringApi.auth(this.getViewMode(), rData);
		}

		if (!isRepeat) {
			this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
		}

        if (this.DocInfo.get_Encrypted() && window["AscDesktopEditor"] && !window["AscDesktopEditor"]["IsLocalFile"](true))
        {
            window["AscDesktopEditor"]["OpenFileCrypt"](this.DocInfo.get_Title(), this.DocInfo.get_Url(), window.openFileCryptCallback);
        }
	};
	baseEditorsApi.prototype._OfflineAppDocumentStartLoad        = function()
	{
		this._OfflineAppDocumentEndLoad();
	};
	baseEditorsApi.prototype._OfflineAppDocumentEndLoad        = function()
	{
	};
	baseEditorsApi.prototype._onOpenCommand                      = function(data)
	{
	};
	baseEditorsApi.prototype._onNeedParams                       = function(data, opt_isPassword)
	{
	};
	baseEditorsApi.prototype.asyncServerIdEndLoaded              = function()
	{
	};
	baseEditorsApi.prototype.asyncFontStartLoaded                = function()
	{
		// здесь прокинуть евент о заморозке меню
		this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
	};
	baseEditorsApi.prototype.asyncImageStartLoaded               = function()
	{
		// здесь прокинуть евент о заморозке меню
	};
	baseEditorsApi.prototype.asyncImagesDocumentStartLoaded      = function()
	{
		// евент о заморозке не нужен... оно и так заморожено
		// просто нужно вывести информацию в статус бар (что началась загрузка картинок)
	};
	baseEditorsApi.prototype.onDocumentContentReady              = function()
	{
		var t = this;
		this.isDocumentLoadComplete = true;
		if (!window['IS_NATIVE_EDITOR']) {
			setInterval(function() {t._autoSave();}, 40);
		}
		this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
		this.sendEvent('asc_onDocumentContentReady');

        if (this.editorId == c_oEditorId.Spreadsheet)
			this.onUpdateDocumentModified(this.asc_isDocumentModified());
	};
	// Save
	baseEditorsApi.prototype.processSavedFile                    = function(url, downloadType)
	{
		if (AscCommon.DownloadType.None !== downloadType)
		{
			this.sendEvent(downloadType, url, function(hasError)
			{
			});
		}
		else
		{
			AscCommon.getFile(url);
		}
	};
	baseEditorsApi.prototype.forceSave = function()
	{
		return this.CoAuthoringApi.forceSave();
	};
	baseEditorsApi.prototype.asc_setIsForceSaveOnUserSave = function(val)
	{
		this.isForceSaveOnUserSave = val;
	};
	baseEditorsApi.prototype._onUpdateDocumentCanSave = function () {
	};
	baseEditorsApi.prototype._onUpdateDocumentCanUndoRedo = function () {
	};
	baseEditorsApi.prototype._saveCheck = function () {
		return false;
	};
	// Переопределяется во всех редакторах
	baseEditorsApi.prototype._haveOtherChanges = function () {
		return false;
	};
	baseEditorsApi.prototype._onSaveCallback = function (e) {
		var t = this;
		var nState;
		if (false == e["saveLock"]) {
			if (this.isLongAction()) {
				// Мы не можем в этот момент сохранять, т.к. попали в ситуацию, когда мы залочили сохранение и успели нажать вставку до ответа
				// Нужно снять lock с сохранения
				this.CoAuthoringApi.onUnSaveLock = function () {
					t.canSave = true;
					t.IsUserSave = false;
					t.lastSaveTime = null;

					if (t.canUnlockDocument) {
						t._unlockDocument();
					}
				};
				this.CoAuthoringApi.unSaveLock();
				return;
			}

			this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);

			this.canUnlockDocument2 = this.canUnlockDocument;
			if (this.canUnlockDocument && this.canStartCoAuthoring) {
				this.CoAuthoringApi.onStartCoAuthoring(true);
			}
			this.canStartCoAuthoring = false;
			this.canUnlockDocument = false;

			this._onSaveCallbackInner();
		} else {
			nState = this.CoAuthoringApi.get_state();
			if (AscCommon.ConnectionState.ClosedCoAuth === nState || AscCommon.ConnectionState.ClosedAll === nState) {
				// Отключаемся от сохранения, соединение потеряно
				this.IsUserSave = false;
				this.canSave = true;
			} else {
				// Если автосохранение, то не будем ждать ответа, а просто перезапустим таймер на немного
				if (!this.IsUserSave) {
					this.canSave = true;
					if (this.canUnlockDocument) {
						this._unlockDocument();
					}
					return;
				}

				setTimeout(function() {
					t.CoAuthoringApi.askSaveChanges(function(event) {
						t._onSaveCallback(event);
					});
				}, 1000);
			}
		}
	};
	// Функция сохранения. Переопределяется во всех редакторах
	baseEditorsApi.prototype._onSaveCallbackInner = function () {
	};
	baseEditorsApi.prototype._autoSave = function () {
		if (this.canSave && !this.isViewMode && (this.canUnlockDocument || 0 !== this.autoSaveGap)) {
			if (this.canUnlockDocument) {
				this.lastSaveTime = new Date();
				// Check edit mode after unlock document http://bugzilla.onlyoffice.com/show_bug.cgi?id=35971
				// Close cell edit without errors (isIdle = true)
				this.asc_Save(true, true);
			} else {
				this._autoSaveInner();
			}
		}
	};
	// Функция автосохранения. Переопределяется во всех редакторах
	baseEditorsApi.prototype._autoSaveInner = function () {
	};
	baseEditorsApi.prototype._prepareSave = function (isIdle) {
		return true;
	};
	// Unlock document when start co-authoring
	baseEditorsApi.prototype._unlockDocument = function () {
		if (this.isDocumentLoadComplete) {
			// Document is load
			this.canUnlockDocument = true;
			this.canStartCoAuthoring = true;
			if (this.canSave) {
				// We can only unlock with delete index
				this.CoAuthoringApi.unLockDocument(false, true, AscCommon.History.GetDeleteIndex());
				this.startCollaborationEditing();
				AscCommon.History.RemovePointsByDeleteIndex();
				this._onUpdateDocumentCanSave();
				this._onUpdateDocumentCanUndoRedo();
				this.canStartCoAuthoring = false;
				this.canUnlockDocument = false;
			} else {
				// ToDo !!!!
			}
		} else {
			// Когда документ еще не загружен, нужно отпустить lock (при быстром открытии 2-мя пользователями)
			this.startCollaborationEditing();
			this.CoAuthoringApi.unLockDocument(false, true);
		}
	};
	// Выставление интервала автосохранения (0 - означает, что автосохранения нет)
	baseEditorsApi.prototype.asc_setAutoSaveGap                  = function(autoSaveGap)
	{
		if (typeof autoSaveGap === "number")
		{
			this.autoSaveGap = autoSaveGap * 1000; // Нам выставляют в секундах
		}
	};
	// send chart message
	baseEditorsApi.prototype.asc_coAuthoringChatSendMessage      = function(message)
	{
		this.CoAuthoringApi.sendMessage(message);
	};
	// get chart messages
	baseEditorsApi.prototype.asc_coAuthoringChatGetMessages      = function()
	{
		this.CoAuthoringApi.getMessages();
	};
	// get users, возвращается массив users
	baseEditorsApi.prototype.asc_coAuthoringGetUsers             = function()
	{
		this.CoAuthoringApi.getUsers();
	};
	// get permissions
	baseEditorsApi.prototype.asc_getEditorPermissions            = function()
	{
		this._coAuthoringInit();
	};
	baseEditorsApi.prototype._onEndPermissions                   = function()
	{
		if (this.isOnFirstConnectEnd && this.isOnLoadLicense)
		{
			this.sendEvent('asc_onGetEditorPermissions', new AscCommon.asc_CAscEditorPermissions());
		}
	};
	// CoAuthoring
	baseEditorsApi.prototype._coAuthoringInit                    = function()
	{
		var t = this;
		//Если User не задан, отключаем коавторинг.
		if (null == this.User || null == this.User.asc_getId())
		{
			this.User = new AscCommon.asc_CUser();
			this.User.setId("Unknown");
			this.User.setUserName("Unknown");
		}
		//в обычном серверном режиме портим ссылку, потому что CoAuthoring теперь имеет встроенный адрес
		//todo надо использовать проверку get_OfflineApp
		if (!(window['NATIVE_EDITOR_ENJINE'] || (this.DocInfo && this.DocInfo.get_OfflineApp())) || window['IS_NATIVE_EDITOR'])
		{
			this.CoAuthoringApi.set_url(null);
		}

		this.CoAuthoringApi.onMessage                 = function(e, clear)
		{
			t.sendEvent('asc_onCoAuthoringChatReceiveMessage', e, clear);
		};
		this.CoAuthoringApi.onServerVersion = function (buildVersion, buildNumber) {
			t.sendEvent('asc_onServerVersion', buildVersion, buildNumber);
		};
		this.CoAuthoringApi.onAuthParticipantsChanged = function(users, userId)
		{
			t.sendEvent("asc_onAuthParticipantsChanged", users, userId);
		};
		this.CoAuthoringApi.onParticipantsChanged     = function(users)
		{
			t.sendEvent("asc_onParticipantsChanged", users);
		};
		this.CoAuthoringApi.onSpellCheckInit          = function(e)
		{
			t.SpellCheckUrl = e;
			t._coSpellCheckInit();
		};
		this.CoAuthoringApi.onSetIndexUser            = function(e)
		{
			AscCommon.g_oIdCounter.Set_UserId('' + e);
		};
		this.CoAuthoringApi.onFirstLoadChangesEnd     = function()
		{
			t.asyncServerIdEndLoaded();
		};
		this.CoAuthoringApi.onFirstConnect            = function()
		{
			if (t.isOnFirstConnectEnd)
			{
				if (t.CoAuthoringApi.get_isAuth()) {
					t.CoAuthoringApi.auth(t.getViewMode(), undefined, t.isIdle());
				} else {
					//первый запрос или ответ не дошел надо повторить открытие
					t.asc_LoadDocument(undefined, true);
				}
			}
			else
			{
				t.isOnFirstConnectEnd = true;
				t._onEndPermissions();
			}
		};
		this.CoAuthoringApi.onLicense                 = function(res)
		{
			t.licenseResult   = res;
			t.isOnLoadLicense = true;
			t._onEndPermissions();
		};
		this.CoAuthoringApi.onLicenseChanged          = function(res)
		{
			t.licenseResult   = res;
			t.isOnLoadLicense = true;
			var oResult = new AscCommon.asc_CAscEditorPermissions();
			oResult.setLicenseType(res);
			t.sendEvent('asc_onLicenseChanged', oResult);
		};
		this.CoAuthoringApi.onWarning                 = function(code)
		{
			t.sendEvent('asc_onError', code || c_oAscError.ID.Warning, c_oAscError.Level.NoCritical);
		};
		this.CoAuthoringApi.onMeta                    = function(data)
		{
			var newDocumentTitle = data["title"];
			if (newDocumentTitle) {
				t.documentTitle = newDocumentTitle;
				if (t.DocInfo) {
					t.DocInfo.asc_putTitle(newDocumentTitle);
				}
			}
			t.sendEvent('asc_onMeta', data);
		};
		this.CoAuthoringApi.onSession = function(data) {
			var code = data["code"];
			var reason = data["reason"];
			var interval = data["interval"];
			var extendSession = true;
			if (c_oCloseCode.sessionIdle == code) {
				var idleTime = t.isIdle();
				if (idleTime > interval) {
					extendSession = false;
				} else {
					t.CoAuthoringApi.extendSession(idleTime);
				}
			} else if (c_oCloseCode.sessionAbsolute == code) {
				extendSession = false;
			}
			if (!extendSession) {
				if (t.asc_Save(false, true)) {
					//enter view mode because save async
					t.setViewModeDisconnect();
					t.disconnectOnSave = {code: code, reason: reason};
				} else {
					t.CoAuthoringApi.disconnect(code, reason);
				}
			}
		};
        this.CoAuthoringApi.onForceSave = function(data) {
            if (AscCommon.c_oAscForceSaveTypes.Button === data.type) {
                if (data.start) {
                    if (null === t.forceSaveButtonTimeout && !t.forceSaveButtonContinue) {
                        t.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveButton);
                    } else {
                        clearInterval(t.forceSaveButtonTimeout);
                    }
                    t.forceSaveButtonTimeout = setTimeout(function() {
                        t.forceSaveButtonTimeout = null;
                        if (t.forceSaveButtonContinue) {
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
                        } else {
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveButton);
                        }
                        t.forceSaveButtonContinue = false;
                        t.sendEvent('asc_onError', Asc.c_oAscError.ID.ForceSaveButton, c_oAscError.Level.NoCritical);
                    }, Asc.c_nMaxConversionTime);
                } else if (data.refuse) {
                    if (t.forceSaveButtonContinue) {
                        t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
                    }
                    t.forceSaveButtonContinue = false;
                } else {
                    if (null !== t.forceSaveButtonTimeout) {
                        clearInterval(t.forceSaveButtonTimeout);
                        t.forceSaveButtonTimeout = null;
                        if (t.forceSaveButtonContinue) {
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
                        } else {
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveButton);
                        }
                        t.forceSaveButtonContinue = false;
                        if (!data.success) {
                            t.sendEvent('asc_onError', Asc.c_oAscError.ID.ForceSaveButton, c_oAscError.Level.NoCritical);
                        }
                    }
                }
            } else {
                if (AscCommon.CollaborativeEditing.Is_Fast() || null !== t.forceSaveTimeoutTimeout) {
                    if (data.start) {
                        if (null === t.forceSaveTimeoutTimeout) {
                            t.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveTimeout);
                        } else {
                            clearInterval(t.forceSaveTimeoutTimeout);
                        }
                        t.forceSaveTimeoutTimeout = setTimeout(function() {
                            t.forceSaveTimeoutTimeout = null;
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveTimeout);
                            t.sendEvent('asc_onError', Asc.c_oAscError.ID.ForceSaveTimeout, c_oAscError.Level.NoCritical);
                        }, Asc.c_nMaxConversionTime);
                    } else {
                        if (null !== t.forceSaveTimeoutTimeout) {
                            clearInterval(t.forceSaveTimeoutTimeout);
                            t.forceSaveTimeoutTimeout = null;
                            t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.ForceSaveTimeout);
                            if (!data.success) {
                                t.sendEvent('asc_onError', Asc.c_oAscError.ID.ForceSaveTimeout, c_oAscError.Level.NoCritical);
                            }
                        }
                    }
                }
            }
        };
		this.CoAuthoringApi.onExpiredToken = function() {
			t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
			t.VersionHistory = null;
			t.sendEvent('asc_onExpiredToken');
		};
		this.CoAuthoringApi.onHasForgotten = function() {
			//todo very bad way, need rewrite
			var isDocumentCanSaveOld = t.isDocumentCanSave;
			var canSaveOld = t.canSave;
			t.isDocumentCanSave = true;
			t.canSave = false;
			t.sendEvent("asc_onDocumentModifiedChanged");
			t.isDocumentCanSave = isDocumentCanSaveOld;
			t.canSave = canSaveOld;
			t.sendEvent("asc_onDocumentModifiedChanged");
		};
		/**
		 * Event об отсоединении от сервера
		 * @param {jQuery} e  event об отсоединении с причиной
		 * @param {Bool} isDisconnectAtAll  окончательно ли отсоединяемся(true) или будем пробовать сделать reconnect(false) + сами отключились
		 * @param {Bool} isCloseCoAuthoring
		 */
		this.CoAuthoringApi.onDisconnect = function(e, error)
		{
			if (AscCommon.ConnectionState.None === t.CoAuthoringApi.get_state())
			{
				t.asyncServerIdEndLoaded();
			}
			if (null != error)
			{
				t.setViewModeDisconnect();
				t.sendEvent('asc_onError', error.code, error.level);
			}
		};
		this.CoAuthoringApi.onDocumentOpen = function (inputWrap) {
			if (AscCommon.EncryptionWorker.isNeedCrypt())
			{
                if (t.fCurCallback) {
                	t.fCurCallback(inputWrap ? inputWrap["data"] : undefined);
                	t.fCurCallback = null;
                }
				return;
			}
			if (inputWrap["data"]) {
				var input = inputWrap["data"];
				switch (input["type"]) {
					case 'reopen':
					case 'open':
						switch (input["status"]) {
							case "updateversion":
							case "ok":
								var urls = input["data"];
								AscCommon.g_oDocumentUrls.init(urls);
								if (null != urls['Editor.bin']) {
									if ('ok' === input["status"] || t.getViewMode()) {
										t._onOpenCommand(urls['Editor.bin']);
									} else {
										t.sendEvent("asc_onDocumentUpdateVersion", function () {
											if (t.isCoAuthoringEnable) {
												t.asc_coAuthoringDisconnect();
											}
											t._onOpenCommand(urls['Editor.bin']);
										})
									}
								} else {
									t.sendEvent("asc_onError", c_oAscError.ID.ConvertationOpenError,
										c_oAscError.Level.Critical);
								}
								break;
							case "needparams":
								t._onNeedParams(input["data"]);
								break;
							case "needpassword":
								t._onNeedParams(null, true);
								break;
							case "err":
								t.sendEvent("asc_onError",
									AscCommon.mapAscServerErrorToAscError(parseInt(input["data"]),
										Asc.c_oAscError.ID.ConvertationOpenError), c_oAscError.Level.Critical);
								break;
						}
						break;
					default:
						if (t.fCurCallback) {
							t.fCurCallback(input);
							t.fCurCallback = null;
						} else {
							t.sendEvent("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
						}
						break;
				}
			}
		};
		this.CoAuthoringApi.onStartCoAuthoring = function (isStartEvent) {
			if (t.isViewMode) {
				return;
			}
			// На старте не нужно ничего делать
			if (isStartEvent) {
				t.startCollaborationEditing();
			} else {
				t._unlockDocument();
			}
		};
		this.CoAuthoringApi.onEndCoAuthoring = function (isStartEvent) {
			if (t.canUnlockDocument) {
				t.canStartCoAuthoring = false;
			} else {
				t.endCollaborationEditing();
			}
		};

		this._coAuthoringInitEnd();
		this.CoAuthoringApi.init(this.User, this.documentId, this.documentCallbackUrl, 'fghhfgsjdgfjs', this.editorId, this.documentFormatSave, this.DocInfo);
	};
	baseEditorsApi.prototype._coAuthoringInitEnd                 = function()
	{
	};
	baseEditorsApi.prototype.startCollaborationEditing           = function()
	{
	};
	baseEditorsApi.prototype.endCollaborationEditing             = function()
	{
	};
	baseEditorsApi.prototype._coAuthoringCheckEndOpenDocument    = function(f)
	{
		if (this.isPreOpenLocks)
		{
			var context = this.CoAuthoringApi;
			var args = Array.prototype.slice.call(arguments, 1);

			// Пока документ еще не загружен, будем сохранять функцию и аргументы
			this.arrPreOpenLocksObjects.push(function()
			{
				f.apply(context, args);
			});
			return true;
		}
		return false;
	};
	baseEditorsApi.prototype._applyPreOpenLocks                  = function()
	{
		this.isPreOpenLocks = false;
		// Применяем все lock-и (ToDo возможно стоит пересмотреть вообще Lock-и)
		for (var i = 0; i < this.arrPreOpenLocksObjects.length; ++i)
		{
			this.arrPreOpenLocksObjects[i]();
		}
		this.arrPreOpenLocksObjects = [];
	};
	// server disconnect
	baseEditorsApi.prototype.asc_coAuthoringDisconnect           = function()
	{
		this.CoAuthoringApi.disconnect();
		this.isCoAuthoringEnable = false;

		// Выставляем view-режим
		this.asc_setViewMode(true);
	};
	baseEditorsApi.prototype.asc_stopSaving                      = function()
	{
		this.incrementCounterLongAction();
	};
	baseEditorsApi.prototype.asc_continueSaving                  = function()
	{
		this.decrementCounterLongAction();
	};
	// SpellCheck
	baseEditorsApi.prototype._coSpellCheckInit                   = function()
	{
	};
	// Images & Charts & TextArts
	baseEditorsApi.prototype.asc_getChartPreviews                = function(chartType)
	{
		return this.chartPreviewManager.getChartPreviews(chartType);
	};
	baseEditorsApi.prototype.asc_getTextArtPreviews              = function()
	{
		return this.textArtPreviewManager.getWordArtStyles();
	};
	baseEditorsApi.prototype.asc_onOpenChartFrame                = function()
	{
		if(this.isMobileVersion){
			return;
		}
		this.isOpenedChartFrame = true;
	};
	baseEditorsApi.prototype.asc_onCloseChartFrame               = function()
	{
		this.isOpenedChartFrame = false;
	};
	baseEditorsApi.prototype.asc_setInterfaceDrawImagePlaceShape = function(elementId)
	{
		this.shapeElementId = elementId;
	};
	baseEditorsApi.prototype.asc_getPropertyEditorShapes         = function()
	{
		return [AscCommon.g_oAutoShapesGroups, AscCommon.g_oAutoShapesTypes];
	};
	baseEditorsApi.prototype.asc_getPropertyEditorTextArts       = function()
	{
		return [AscCommon.g_oPresetTxWarpGroups, AscCommon.g_PresetTxWarpTypes];
	};
	// Add image
	baseEditorsApi.prototype._addImageUrl                        = function()
	{
	};
	baseEditorsApi.prototype.asc_addImage                        = function()
	{
		var t = this;
		AscCommon.ShowImageFileDialog(this.documentId, this.documentUserId, this.CoAuthoringApi.get_jwt(), function(error, files)
		{
			t._uploadCallback(error, files);
		}, function(error)
		{
			if (c_oAscError.ID.No !== error)
			{
				t.sendEvent("asc_onError", error, c_oAscError.Level.NoCritical);
			}
			t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
		});
	};
	baseEditorsApi.prototype._uploadCallback                     = function(error, files)
	{
		var t = this;
		if (c_oAscError.ID.No !== error)
		{
			this.sendEvent("asc_onError", error, c_oAscError.Level.NoCritical);
		}
		else
		{
			this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
			AscCommon.UploadImageFiles(files, this.documentId, this.documentUserId, this.CoAuthoringApi.get_jwt(), function(error, urls)
			{
				if (c_oAscError.ID.No !== error)
				{
					t.sendEvent("asc_onError", error, c_oAscError.Level.NoCritical);
				}
				else
				{
					t._addImageUrl(urls);
				}
				t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
			});
		}
	};

	//метод, который подменяет callback загрузки в каждом редакторе, TODO: переделать, сделать одинаково в о всех редакторах
	baseEditorsApi.prototype.asc_replaceLoadImageCallback = function(fCallback)
	{
	};

	baseEditorsApi.prototype.asc_loadLocalImageAndAction = function(sLocalImage, fCallback)
	{
		var _loadedUrl = this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalImage), 1);
		if (_loadedUrl != null)
		    fCallback(_loadedUrl);
        else
        	this.asc_replaceLoadImageCallback(fCallback);
	};

	baseEditorsApi.prototype.asc_checkImageUrlAndAction = function(sImageUrl, fCallback)
	{
		var oThis = this;
		this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
		var fCallback2 = function()
		{
			oThis.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
			fCallback.apply(oThis, arguments);
		};
		var sLocalImage = AscCommon.g_oDocumentUrls.getImageLocal(sImageUrl);
		if (sLocalImage)
		{
			this.asc_loadLocalImageAndAction(sLocalImage, fCallback2);
			return;
		}

		AscCommon.sendImgUrls(oThis, [sImageUrl], function(data)
		{
			if (data[0] && data[0].path != null)
			{
				oThis.asc_loadLocalImageAndAction(AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path), fCallback2);
			}
		}, this.editorId === c_oEditorId.Spreadsheet);
	};

	baseEditorsApi.prototype.asc_addOleObject = function(oPluginData)
	{
		if(this.isViewMode){
			return;
		}
		Asc.CPluginData_wrap(oPluginData);
		var oThis      = this;
		var sImgSrc    = oPluginData.getAttribute("imgSrc");
		var nWidthPix  = oPluginData.getAttribute("widthPix");
		var nHeightPix = oPluginData.getAttribute("heightPix");
		var fWidth     = oPluginData.getAttribute("width");
		var fHeight    = oPluginData.getAttribute("height");
		var sData      = oPluginData.getAttribute("data");
		var sGuid      = oPluginData.getAttribute("guid");
		if (typeof sImgSrc === "string" && sImgSrc.length > 0 && typeof sData === "string"
			&& typeof sGuid === "string" && sGuid.length > 0
			&& AscFormat.isRealNumber(nWidthPix) && AscFormat.isRealNumber(nHeightPix)
			&& AscFormat.isRealNumber(fWidth) && AscFormat.isRealNumber(fHeight)
		)

			this.asc_checkImageUrlAndAction(sImgSrc, function(oImage)
			{
				oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src), sData, sGuid, fWidth, fHeight, nWidthPix, nHeightPix);
			});
	};

	baseEditorsApi.prototype.asc_editOleObject = function(oPluginData)
	{
		if(this.isViewMode){
			return;
		}
		Asc.CPluginData_wrap(oPluginData);
		var oThis      = this;
		var bResize    = oPluginData.getAttribute("resize");
		var sImgSrc    = oPluginData.getAttribute("imgSrc");
		var oOleObject = AscCommon.g_oTableId.Get_ById(oPluginData.getAttribute("objectId"));
		var nWidthPix  = oPluginData.getAttribute("widthPix");
		var nHeightPix = oPluginData.getAttribute("heightPix");
		var sData      = oPluginData.getAttribute("data");
		if (typeof sImgSrc === "string" && sImgSrc.length > 0 && typeof sData === "string"
			&& oOleObject && AscFormat.isRealNumber(nWidthPix) && AscFormat.isRealNumber(nHeightPix))
		{
			this.asc_checkImageUrlAndAction(sImgSrc, function(oImage)
			{
				oThis.asc_editOleObjectAction(bResize, oOleObject, AscCommon.g_oDocumentUrls.getImageLocal(oImage.src), sData, nWidthPix, nHeightPix);
			});
		}
	};

	baseEditorsApi.prototype.asc_addOleObjectAction = function(sLocalUrl, sData, sApplicationId, fWidth, fHeight)
	{
	};

	baseEditorsApi.prototype.asc_editOleObjectAction = function(bResize, oOleObject, sImageUrl, sData, nPixWidth, nPixHeight)
	{
	};

	baseEditorsApi.prototype.asc_selectSearchingResults = function(value)
	{
		if (this.selectSearchingResults === value)
		{
			return;
		}
		this.selectSearchingResults = value;
		this._selectSearchingResults(value);
	};


	baseEditorsApi.prototype.asc_startEditCurrentOleObject = function(){

	};
	// Version History
	baseEditorsApi.prototype.asc_showRevision   = function(newObj)
	{
	};
	baseEditorsApi.prototype.asc_undoAllChanges = function()
	{
	};
	baseEditorsApi.prototype.asc_Save = function (isAutoSave, isIdle) {
		var t = this;
		var res = false;
		if (this.canSave && this._saveCheck()) {
			this.IsUserSave = !isAutoSave;

			if (this.asc_isDocumentCanSave() || AscCommon.History.Have_Changes() || this._haveOtherChanges() ||
				this.canUnlockDocument || this.forceSaveUndoRequest) {
				if (this._prepareSave(isIdle)) {
					// Не даем пользователю сохранять, пока не закончится сохранение (если оно началось)
					this.canSave = false;
					this.CoAuthoringApi.askSaveChanges(function (e) {
						t._onSaveCallback(e);
					});
					res = true;
				}
			} else if (this.isForceSaveOnUserSave && this.IsUserSave) {
				this.forceSave();
			}
		}
		return res;
	};
	/**
	 * Эта функция возвращает true, если есть изменения или есть lock-и в документе
	 */
	baseEditorsApi.prototype.asc_isDocumentCanSave = function()
	{
		return this.isDocumentCanSave;
	};
	baseEditorsApi.prototype.asc_getCanUndo = function()
	{
		return AscCommon.History.Can_Undo();
	};
	baseEditorsApi.prototype.asc_getCanRedo = function()
	{
		return AscCommon.History.Can_Redo();
	};
	// Offline mode
	baseEditorsApi.prototype.asc_isOffline  = function()
	{
		return (window.location.protocol.indexOf("file") == 0) ? true : false;
	};
	baseEditorsApi.prototype.asc_getUrlType = function(url)
	{
		return AscCommon.getUrlType(url);
	};

	baseEditorsApi.prototype.openDocument  = function()
	{
	};
	baseEditorsApi.prototype.openDocumentFromZip  = function()
	{
	};
	baseEditorsApi.prototype.onEndLoadDocInfo = function()
	{
		if (this.isLoadFullApi && this.DocInfo)
		{
			if (this.DocInfo.get_OfflineApp())
			{
				if (this.editorId === c_oEditorId.Spreadsheet && this.isChartEditor)
				{
					this.onEndLoadFile(AscCommonExcel.getEmptyWorkbook());
				}
				else
				{
					this._OfflineAppDocumentStartLoad();
				}
			}
			this.onEndLoadFile(null);
		}
	};
	baseEditorsApi.prototype.onEndLoadFile = function(result)
	{
		if (result)
		{
			this.openResult = result;
		}
		if (this.isLoadFullApi && this.DocInfo && this.openResult)
		{
			this.openDocument(this.openResult);
			this.openResult = null;
		}

	};
	baseEditorsApi.prototype._onEndLoadSdk = function()
	{
		AscCommon.g_oTableId.init();

		// init drag&drop
		var t = this;
		AscCommon.InitDragAndDrop(this.HtmlElement, function(error, files)
		{
			t._uploadCallback(error, files);
		});

		AscFonts.g_fontApplication.Init();

		this.FontLoader  = AscCommon.g_font_loader;
		this.ImageLoader = AscCommon.g_image_loader;
		this.FontLoader.put_Api(this);
		this.ImageLoader.put_Api(this);
		this.FontLoader.SetStandartFonts();

		this.chartPreviewManager   = new AscCommon.ChartPreviewManager();
		this.textArtPreviewManager = new AscCommon.TextArtPreviewManager();

		AscFormat.initStyleManager();

		if (null !== this.tmpFocus)
		{
			this.asc_enableKeyEvents(this.tmpFocus);
		}

		this.pluginsManager     = Asc.createPluginsManager(this);

		this.macros = new AscCommon.CDocumentMacros();
	};

	baseEditorsApi.prototype.sendStandartTextures = function()
	{
	    if (this.isSendStandartTextures)
	        return;

	    this.isSendStandartTextures = true;

		var _count = AscCommon.g_oUserTexturePresets.length;
		var arr    = new Array(_count);
		for (var i = 0; i < _count; ++i)
		{
			arr[i]       = new AscCommon.asc_CTexture();
			arr[i].Id    = i;
			arr[i].Image = AscCommon.g_oUserTexturePresets[i];
			this.ImageLoader.LoadImage(AscCommon.g_oUserTexturePresets[i], 1);
		}

		this.sendEvent('asc_onInitStandartTextures', arr);
	};

	baseEditorsApi.prototype.sendMathToMenu = function ()
	{
		if (this.MathMenuLoad)
			return;
		// GENERATE_IMAGES
		//var _MathPainter = new CMathPainter(this.m_oWordControl.m_oApi);
		//_MathPainter.StartLoad();
		//return;
		var _MathPainter = new AscFormat.CMathPainter(this);
		_MathPainter.Generate();
		this.MathMenuLoad = true;
	};

	baseEditorsApi.prototype.sendMathTypesToMenu         = function(_math)
	{
		this.sendEvent("asc_onMathTypes", _math);
	};

	baseEditorsApi.prototype.asyncFontEndLoaded_MathDraw = function(Obj)
	{
		this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
		Obj.Generate2();
	};

	baseEditorsApi.prototype.sendColorThemes = function (theme) {
		var result = AscCommon.g_oUserColorScheme.slice();

		// theme colors
		var elem, _c;
		var _extra = theme.extraClrSchemeLst;
		var _count = _extra.length;
		var _rgba = {R: 0, G: 0, B: 0, A: 255};
		for (var i = 0; i < _count; ++i) {
			var _scheme = _extra[i].clrScheme;

			elem = new AscCommon.CAscColorScheme();
			elem.name = _scheme.name;

			_scheme.colors[8].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[8].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[12].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[12].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[9].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[9].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[13].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[13].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[0].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[0].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[1].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[1].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[2].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[2].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[3].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[3].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[4].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[4].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[5].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[5].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[11].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[11].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

			_scheme.colors[10].Calculate(theme, null, null, null, _rgba);
			_c = _scheme.colors[10].RGBA;
			elem.colors.push(new AscCommon.CColor(_c.R, _c.G, _c.B));

            result.push(elem)
		}

		this.sendEvent("asc_onSendThemeColorSchemes", result);
		return result;
	};

	// plugins
	baseEditorsApi.prototype._checkLicenseApiFunctions   = function()
	{
		return this.licenseResult && true === this.licenseResult['plugins'];
	};

	baseEditorsApi.prototype.asc_pluginsRegister   = function(basePath, plugins)
	{
		if (null != this.pluginsManager)
			this.pluginsManager.register(basePath, plugins);
	};
	baseEditorsApi.prototype.asc_pluginRun         = function(guid, variation, pluginData)
	{
		if (null != this.pluginsManager)
			this.pluginsManager.run(guid, variation, pluginData);
	};
	baseEditorsApi.prototype.asc_pluginResize      = function(pluginData)
	{
		if (null != this.pluginsManager)
			this.pluginsManager.runResize(pluginData);
	};
	baseEditorsApi.prototype.asc_pluginButtonClick = function(id)
	{
		if (null != this.pluginsManager)
			this.pluginsManager.buttonClick(id);
	};

	baseEditorsApi.prototype.asc_pluginEnableMouseEvents = function(isEnable)
	{
		if (!this.pluginsManager)
			return;

		this.pluginsManager.onEnableMouseEvents(isEnable);
	};

    baseEditorsApi.prototype.isEnabledDropTarget = function()
    {
    	return true;
    };
    baseEditorsApi.prototype.beginInlineDropTarget = function(e)
    {
    };
    baseEditorsApi.prototype.endInlineDropTarget = function(e)
    {
    };

    baseEditorsApi.prototype["pluginMethod_GetFontList"] = function()
    {
    	return AscFonts.g_fontApplication.g_fontSelections.SerializeList();
    };

	baseEditorsApi.prototype["pluginMethod_PasteHtml"] = function(htmlText)
	{
		if (!AscCommon.g_clipboardBase)
			return null;

		var _elem = document.createElement("div");

		if (this.editorId == c_oEditorId.Word || this.editorId == c_oEditorId.Presentation)
		{
			var textPr = this.get_TextProps();
			if (textPr)
			{
				if (undefined !== textPr.TextPr.FontSize)
					_elem.style.fontSize = textPr.TextPr.FontSize + "pt";

				_elem.style.fontWeight = (true === textPr.TextPr.Bold) ? "bold" : "normal";
				_elem.style.fontStyle = (true === textPr.TextPr.Italic) ? "italic" : "normal";

				var _color = textPr.TextPr.Color;
				if (_color)
                    _elem.style.color = "rgb(" + _color.r + "," + _color.g + "," + _color.b + ")";
				else
                    _elem.style.color = "rgb(0,0,0)";
			}
		}
		else if (this.editorId == c_oEditorId.Spreadsheet)
		{
			var props = this.asc_getCellInfo();

			if (props && props.font)
			{
				if (undefined != props.font.size)
					_elem.style.fontSize = props.font.size + "pt";

				_elem.style.fontWeight = (true === props.font.bold) ? "bold" : "normal";
				_elem.style.fontStyle = (true === props.font.italic) ? "italic" : "normal";
			}
		}

		_elem.innerHTML = htmlText;
		document.body.appendChild(_elem);
		this.incrementCounterLongAction();
		var b_old_save_format = AscCommon.g_clipboardBase.bSaveFormat;
        AscCommon.g_clipboardBase.bSaveFormat = true;
		this.asc_PasteData(AscCommon.c_oAscClipboardDataFormat.HtmlElement, _elem, null, null, null, true);
		this.decrementCounterLongAction();

		if (true)
		{
			var fCallback = function ()
            {
                document.body.removeChild(_elem);
                _elem = null;
                AscCommon.g_clipboardBase.bSaveFormat = b_old_save_format;
            };
			if(this.checkLongActionCallback(fCallback, null)){
                fCallback();
			}
		}
		else
		{
			document.body.removeChild(_elem);
			_elem = null;
            AscCommon.g_clipboardBase.bSaveFormat = b_old_save_format;
		}
	};

	baseEditorsApi.prototype["pluginMethod_PasteText"] = function(text)
	{
		if (!AscCommon.g_clipboardBase)
			return null;

		this.asc_PasteData(AscCommon.c_oAscClipboardDataFormat.Text, text);
	};

	baseEditorsApi.prototype["pluginMethod_GetMacros"] = function()
	{
		return this.asc_getMacros();
	};

	baseEditorsApi.prototype["pluginMethod_SetMacros"] = function(data)
	{
		return this.asc_setMacros(data);
	};

	baseEditorsApi.prototype["pluginMethod_StartAction"] = function(type, description)
	{
		this.sync_StartAction((type == "Block") ? c_oAscAsyncActionType.BlockInteraction : c_oAscAsyncActionType.Information, description);
	};

	baseEditorsApi.prototype["pluginMethod_EndAction"] = function(type, description)
	{
		this.sync_EndAction((type == "Block") ? c_oAscAsyncActionType.BlockInteraction : c_oAscAsyncActionType.Information, description);

        if (this._callbackPluginEndAction)
		{
			this._callbackPluginEndAction.call(this);
		}
	};

    baseEditorsApi.prototype["pluginMethod_OnEncryption"] = function(obj)
    {
        var _editor = window["Asc"]["editor"] ? window["Asc"]["editor"] : window.editor;
        switch (obj.type)
        {
            case "generatePassword":
            {
                if ("" == obj["password"])
                {
                    _editor.sendEvent("asc_onError", "There is no connection with the blockchain", c_oAscError.Level.Critical);
                    return;
                }

                var _ret = _editor.asc_nativeGetFile3();
                AscCommon.EncryptionWorker.isPasswordCryptoPresent = true;
                window["AscDesktopEditor"]["buildCryptedStart"](_ret.data, _ret.header, obj["password"], obj["docinfo"] ? obj["docinfo"] : "");
                break;
            }
            case "getPasswordByFile":
            {
                if ("" != obj["password"])
                {
                    var _param = ("<m_sPassword>" + AscCommon.CopyPasteCorrectString(obj["password"]) + "</m_sPassword>");
                    _editor.currentPassword = obj["password"];
                    _editor.currentDocumentHash = obj["hash"];
                    _editor.currentDocumentInfo = obj["docinfo"];

                    AscCommon.EncryptionWorker.isPasswordCryptoPresent = true;

                    if (window.isNativeOpenPassword)
                    {
                        window["AscDesktopEditor"]["NativeViewerOpen"](obj["password"]);
                    }
                    else
					{
						window["AscDesktopEditor"]["SetAdvancedOptions"](_param);
                    }
                }
                else
                {
                    this._onNeedParams(undefined, true);
                }
                break;
            }
            case "encryptData":
            case "decryptData":
            {
                AscCommon.EncryptionWorker.receiveChanges(obj);
                break;
            }
        }
    };

	// Builder
	baseEditorsApi.prototype.asc_nativeInitBuilder = function()
	{
		this.asc_setDocInfo(new Asc.asc_CDocInfo());
	};
	baseEditorsApi.prototype.asc_SetSilentMode     = function()
	{
	};
	baseEditorsApi.prototype.asc_canPaste          = function()
	{
		return false;
	};
	baseEditorsApi.prototype.asc_Recalculate       = function()
	{
	};

	// Native
	baseEditorsApi.prototype['asc_nativeCheckPdfRenderer'] = function (_memory1, _memory2) {
		if (true) {
			// pos не должен минимизироваться!!!

			_memory1.Copy = _memory1["Copy"];
			_memory1.ClearNoAttack = _memory1["ClearNoAttack"];
			_memory1.WriteByte = _memory1["WriteByte"];
			_memory1.WriteBool = _memory1["WriteBool"];
			_memory1.WriteLong = _memory1["WriteLong"];
			_memory1.WriteDouble = _memory1["WriteDouble"];
			_memory1.WriteString = _memory1["WriteString"];
			_memory1.WriteString2 = _memory1["WriteString2"];

			_memory2.Copy = _memory1["Copy"];
			_memory2.ClearNoAttack = _memory1["ClearNoAttack"];
			_memory2.WriteByte = _memory1["WriteByte"];
			_memory2.WriteBool = _memory1["WriteBool"];
			_memory2.WriteLong = _memory1["WriteLong"];
			_memory2.WriteDouble = _memory1["WriteDouble"];
			_memory2.WriteString = _memory1["WriteString"];
			_memory2.WriteString2 = _memory1["WriteString2"];
		}

		var _printer = new AscCommon.CDocumentRenderer();
		_printer.Memory = _memory1;
		_printer.VectorMemoryForPrint = _memory2;
		return _printer;
	};

	// input
	baseEditorsApi.prototype.Begin_CompositeInput = function()
	{
	};
	baseEditorsApi.prototype.Add_CompositeText = function(nCharCode)
	{
	};
	baseEditorsApi.prototype.Remove_CompositeText = function(nCount)
	{
	};
	baseEditorsApi.prototype.Replace_CompositeText = function(arrCharCodes)
	{
	};
	baseEditorsApi.prototype.Set_CursorPosInCompositeText = function(nPos)
	{
	};
	baseEditorsApi.prototype.Get_CursorPosInCompositeText = function()
	{
	};
	baseEditorsApi.prototype.End_CompositeInput = function()
	{
	};
	baseEditorsApi.prototype.Get_MaxCursorPosInCompositeText = function()
	{
	};
	baseEditorsApi.prototype.Input_UpdatePos = function()
	{
	};
	baseEditorsApi.prototype["setInputParams"] = function(_obj)
	{
		window["AscInputMethod"] = window["AscInputMethod"] || {};

		for (var _prop in _obj)
		{
			window["AscInputMethod"][_prop] = _obj[_prop];
		}
	};

	baseEditorsApi.prototype.asc_addSignatureLine = function (sGuid, sSigner, sSigner2, sEmail, Width, Height, sImgUrl) {

    };
	baseEditorsApi.prototype.asc_getAllSignatures = function () {
		return [];
	};

	baseEditorsApi.prototype.asc_CallSignatureDblClickEvent = function(sGuid){

	};

	// signatures
	baseEditorsApi.prototype.asc_AddSignatureLine2 = function(_obj)
	{
		var _w = 50;
		var _h = 50;
		var _w_pix = (_w * AscCommon.g_dKoef_mm_to_pix) >> 0;
		var _h_pix = (_h * AscCommon.g_dKoef_mm_to_pix) >> 0;
		var _canvas = document.createElement("canvas");
		_canvas.width = _w_pix;
		_canvas.height = _h_pix;
		var _ctx = _canvas.getContext("2d");
		_ctx.fillStyle = "#000000";
		_ctx.strokeStyle = "#000000";
		_ctx.font = "10pt 'Courier New'";
		_ctx.lineWidth = 3;

		_ctx.beginPath();
		var _y_line = (_h_pix >> 1) + 0.5;
		_ctx.moveTo(0, _y_line);
		_ctx.lineTo(_w_pix, _y_line);
		_ctx.stroke();
		_ctx.beginPath();

		_ctx.lineWidth = 2;
		_y_line -= 10;
		_ctx.moveTo(10, _y_line);
		_ctx.lineTo(25, _y_line - 10);
		_ctx.lineTo(10, _y_line - 20);
		_ctx.stroke();
		_ctx.beginPath();

		_ctx.fillText(_obj.asc_getSigner1(), 10, _y_line + 25);
		_ctx.fillText(_obj.asc_getSigner2(), 10, _y_line + 40);
		_ctx.fillText(_obj.asc_getEmail(), 10, _y_line + 55);

		var _url = _canvas.toDataURL("image/png");
		_canvas = null;

		var _args = [AscCommon.CreateGUID(), _obj.asc_getSigner1(), _obj.asc_getSigner2(), _obj.asc_getEmail(), _w, _h, _url];

		this.ImageLoader.LoadImagesWithCallback([_url], function(_args) {
			this.asc_addSignatureLine(_args[0], _args[1], _args[2], _args[3], _args[4], _args[5], _args[6]);
		}, _args);
	};

	baseEditorsApi.prototype.asc_getRequestSignatures = function()
	{
		var _sigs = this.asc_getAllSignatures();
		var _sigs_ret = [];

		var _found;
		for (var i = _sigs.length - 1; i >= 0; i--)
		{
			var _sig = _sigs[i];
			_found = false;

			for (var j = this.signatures.length - 1; j >= 0; j--)
			{
				if (this.signatures[j].guid == _sig.id)
				{
					_found = true;
					break;
				}
			}

			if (!_found)
			{
				var _add_sig = new AscCommon.asc_CSignatureLine();
				_add_sig.guid = _sig.id;
				_add_sig.signer1 = _sig.signer;
				_add_sig.signer2 = _sig.signer2;
				_add_sig.email = _sig.email;

				_sigs_ret.push(_add_sig);
			}
		}

		return _sigs_ret;
	};

	baseEditorsApi.prototype.asc_Sign = function(id, guid, url1, url2)
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["Sign"](id, guid, url1, url2);
	};
	baseEditorsApi.prototype.asc_RequestSign = function(guid)
	{
		var signGuid = (guid == "unvisibleAdd") ? AscCommon.CreateGUID() : guid;

		if (window["asc_LocalRequestSign"])
			window["asc_LocalRequestSign"](signGuid);
	};

	baseEditorsApi.prototype.asc_ViewCertificate = function(id)
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["ViewCertificate"](parseInt("" + id)); // integer or string!
	};

	baseEditorsApi.prototype.asc_SelectCertificate = function()
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["SelectCertificate"]();
	};

	baseEditorsApi.prototype.asc_GetDefaultCertificate = function()
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["GetDefaultCertificate"]();
	};

	baseEditorsApi.prototype.asc_getSignatures = function()
	{
		return this.signatures;
	};

	baseEditorsApi.prototype.asc_RemoveSignature = function(guid)
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["RemoveSignature"](guid);
	};

	baseEditorsApi.prototype.asc_RemoveAllSignatures = function()
	{
		if (window["AscDesktopEditor"])
			window["AscDesktopEditor"]["RemoveAllSignatures"]();
	};

	baseEditorsApi.prototype.asc_isSignaturesSupport = function()
	{
		if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsSignaturesSupport"])
			return window["AscDesktopEditor"]["IsSignaturesSupport"]();
		return false;
	};
    baseEditorsApi.prototype.asc_isProtectionSupport = function()
    {
        if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["IsProtectionSupport"])
            return window["AscDesktopEditor"]["IsProtectionSupport"]();
        return false;
    };

	baseEditorsApi.prototype.asc_gotoSignature = function(guid)
	{
		if (window["AscDesktopEditor"] && window["asc_IsVisibleSign"] && window["asc_IsVisibleSign"](guid))
		{
			if (this.asc_MoveCursorToSignature)
				this.asc_MoveCursorToSignature(guid);
		}
	};

	baseEditorsApi.prototype.asc_getSignatureSetup = function(guid)
	{
		var _sigs = this.asc_getAllSignatures();

		for (var i = _sigs.length - 1; i >= 0; i--)
		{
			var _sig = _sigs[i];
			if (_sig.id == guid)
			{
				var _add_sig = new AscCommon.asc_CSignatureLine();
				_add_sig.guid = _sig.id;
				_add_sig.signer1 = _sig.signer;
				_add_sig.signer2 = _sig.signer2;
				_add_sig.email = _sig.email;

				_add_sig.isrequested = true;
				for (var j = 0; j < this.signatures.length; j++)
				{
					var signDoc = this.signatures[j];
					if (signDoc.guid == _add_sig.guid)
					{
						_add_sig.valid = signDoc.valid;
						_add_sig.isrequested = false;
						break;
					}
				}

				return _add_sig;
			}
		}

		return null;
	};

	baseEditorsApi.prototype.asc_getSignatureImage = function (sGuid) {

		var count = this.signatures.length;
		for (var i = 0; i < count; i++)
		{
			if (this.signatures[i].guid == sGuid)
				return this.signatures[i].image;
		}
		return "";
    };

	baseEditorsApi.prototype.asc_getSessionToken = function () {
		return this.CoAuthoringApi.get_jwt()
	};

	baseEditorsApi.prototype.asc_InputClearKeyboardElement = function()
	{
		if (AscCommon.g_inputContext)
			AscCommon.g_inputContext.nativeFocusElement = null;
	};

	baseEditorsApi.prototype.onKeyDown = function(e)
	{
	};
	baseEditorsApi.prototype.onKeyPress = function(e)
	{
	};
	baseEditorsApi.prototype.onKeyUp = function(e)
	{
	};
	/**
	 * Получаем текст (в виде массива юникодных значений), который будет добавлен на ивенте KeyDown
	 * @param e
	 * @returns {Number[]}
	 */
	baseEditorsApi.prototype.getAddedTextOnKeyDown = function(e)
	{
		return [];
	};
	baseEditorsApi.prototype.pre_Paste = function(_fonts, _images, callback)
	{
	};

	baseEditorsApi.prototype.asc_Remove = function()
	{
		if (AscCommon.g_inputContext)
			AscCommon.g_inputContext.emulateKeyDownApi(46);
	};

	// System input
	baseEditorsApi.prototype.SetTextBoxInputMode = function(bIsEnable)
	{
		AscCommon.TextBoxInputMode = bIsEnable;
		if (AscCommon.g_inputContext)
			AscCommon.g_inputContext.systemInputEnable(AscCommon.TextBoxInputMode);
	};
	baseEditorsApi.prototype.GetTextBoxInputMode = function()
	{
		return AscCommon.TextBoxInputMode;
	};

	baseEditorsApi.prototype.asc_OnHideContextMenu = function()
	{
	};
	baseEditorsApi.prototype.asc_OnShowContextMenu = function()
	{
	};

	baseEditorsApi.prototype.isIdle = function()
	{
		// пока не стартовали - считаем работаем
		if (0 == this.lastWorkTime)
			return 0;

		// если плагин работает - то и мы тоже
		if (this.pluginsManager && this.pluginsManager.isWorked())
			return 0;

		if (this.isEmbedVersion)
			return 0;

		if (!this.canSave || !this._saveCheck())
			return 0;

		return new Date().getTime() - this.lastWorkTime;
	};

	baseEditorsApi.prototype.checkLastWork = function()
	{
		this.lastWorkTime = new Date().getTime();
	};

	baseEditorsApi.prototype.setViewModeDisconnect = function()
	{
		// Посылаем наверх эвент об отключении от сервера
		this.sendEvent('asc_onCoAuthoringDisconnect');
		// И переходим в режим просмотра т.к. мы не можем сохранить файл
		this.asc_setViewMode(true);
	};

	baseEditorsApi.prototype.asc_setCurrentPassword = function(password)
	{
		this.currentPassword = password;
		this.asc_Save(false, undefined, true);
	};
	baseEditorsApi.prototype.asc_resetPassword = function()
	{
		this.currentPassword = "";
		this.asc_Save(false, undefined, true);
	};

	baseEditorsApi.prototype.asc_setMacros = function(sData)
	{
		if (!this.macros)
			return true;

		if (true === AscCommon.CollaborativeEditing.Get_GlobalLock())
			return true;

		AscCommon.CollaborativeEditing.OnStart_CheckLock();
		this.macros.CheckLock();

		if (this.editorId == AscCommon.c_oEditorId.Spreadsheet)
		{
			var locker = Asc.editor.wb.getWorksheet().objectRender.objectLocker;
			locker.addObjectId(this.macros.Get_Id());

			var _this = this;
			locker.checkObjects(function(bNoLock) {
				if (bNoLock)
				{
					AscCommon.History.Create_NewPoint(AscDFH.historydescription_DocumentMacros_Data);
					_this.macros.SetData(sData);
				}
			});
		}
		else
		{
			if (false === AscCommon.CollaborativeEditing.OnEnd_CheckLock(false))
			{
				AscCommon.History.Create_NewPoint(AscDFH.historydescription_DocumentMacros_Data);
				this.macros.SetData(sData);
			}
		}
	};
	baseEditorsApi.prototype.asc_getMacros = function()
	{
		return this.macros.GetData();
	};

	function parseCSV(text, options) {
		var delimiterChar;
		if (options.asc_getDelimiterChar()) {
			delimiterChar = options.asc_getDelimiterChar();
		} else {
			switch (options.asc_getDelimiter()) {
				case AscCommon.c_oAscCsvDelimiter.None:
					delimiterChar = undefined;
					break;
				case AscCommon.c_oAscCsvDelimiter.Tab:
					delimiterChar = "\t";
					break;
				case AscCommon.c_oAscCsvDelimiter.Semicolon:
					delimiterChar = ";";
					break;
				case AscCommon.c_oAscCsvDelimiter.Colon:
					delimiterChar = ":";
					break;
				case AscCommon.c_oAscCsvDelimiter.Comma:
					delimiterChar = ",";
					break;
				case AscCommon.c_oAscCsvDelimiter.Space:
					delimiterChar = " ";
					break;
			}
		}
		var matrix = [];
		var rows = text.match(/[^\r\n]+/g);
		for (var i = 0; i < rows.length; ++i) {
			var row = rows[i];
			//todo quotes
			matrix.push(row.split(delimiterChar));
		}
		return matrix;
	}

	baseEditorsApi.prototype.asc_decodeBuffer = function(buffer, options, callback) {
		var reader = new FileReader();
		//todo onerror
		reader.onload = reader.onerror = function(e) {
			var text = e.target.result ? e.target.result : "";
			if (options instanceof Asc.asc_CCSVAdvancedOptions) {
				callback(parseCSV(text, options));
			} else {
				callback(text.match(/[^\r\n]+/g));
			}
		};

		reader.readAsText(new Blob([buffer]), AscCommon.c_oAscEncodings[options.asc_getCodePage()][2]);
	};

	//----------------------------------------------------------export----------------------------------------------------
	window['AscCommon']                = window['AscCommon'] || {};
	window['AscCommon'].baseEditorsApi = baseEditorsApi;

	prot = baseEditorsApi.prototype;
	prot['asc_selectSearchingResults'] = prot.asc_selectSearchingResults;
})(window);

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

AscCommon.baseEditorsApi.prototype._onEndPermissions = function () {
	if (this.isOnFirstConnectEnd && this.isOnLoadLicense) {
		var oResult = new AscCommon.asc_CAscEditorPermissions();
		if (null !== this.licenseResult) {
			var type = this.licenseResult['type'];
			oResult.setLicenseType(type);
			oResult.setCanBranding(this.licenseResult['branding']);
			oResult.setIsLight(this.licenseResult['light']);
			oResult.setLicenseMode(this.licenseResult['mode']);
			oResult.setRights(this.licenseResult['rights']);
			oResult.setBuildVersion(this.licenseResult['buildVersion']);
			oResult.setBuildNumber(this.licenseResult['buildNumber']);
		}
		this.sendEvent('asc_onGetEditorPermissions', oResult);
	}
};

/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

(function (window, undefined)
{
	window['Asc'] = window['Asc'] || {};
// ---------------------------------------------------------------
	function CAscTableStyle()
	{
		this.Id = "";
		this.Type = 0;
		this.Image = "";
	}

	CAscTableStyle.prototype.get_Id = function ()
	{
		return this.Id;
	};
	CAscTableStyle.prototype.get_Image = function ()
	{
		return this.Image;
	};
	CAscTableStyle.prototype.get_Type = function ()
	{
		return this.Type;
	};
	window['Asc']['CAscTableStyle'] = window['Asc'].CAscTableStyle = CAscTableStyle;
	CAscTableStyle.prototype['get_Id'] = CAscTableStyle.prototype.get_Id;
	CAscTableStyle.prototype['get_Image'] = CAscTableStyle.prototype.get_Image;
	CAscTableStyle.prototype['get_Type'] = CAscTableStyle.prototype.get_Type;

// ---------------------------------------------------------------
// CBackground
// Value : тип заливки(прозрачная или нет),
// Color : { r : 0, g : 0, b : 0 }
	function CBackground(obj)
	{
		if (obj)
		{
			if (obj.Unifill && obj.Unifill.fill && obj.Unifill.fill.type === window['Asc'].c_oAscFill.FILL_TYPE_SOLID && obj.Unifill.fill.color)
			{
				this.Color = AscCommon.CreateAscColor(obj.Unifill.fill.color);
			}
			else
			{
				this.Color = (undefined != obj.Color && null != obj.Color) ? AscCommon.CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) : null;
			}
			this.Value = (undefined != obj.Value) ? obj.Value : null;
		}
		else
		{
			this.Color = AscCommon.CreateAscColorCustom(0, 0, 0);
			this.Value = 1;
		}
	}

	CBackground.prototype.get_Color = function ()
	{
		return this.Color;
	};
	CBackground.prototype.put_Color = function (v)
	{
		this.Color = (v) ? v : null;
	};
	CBackground.prototype.get_Value = function ()
	{
		return this.Value;
	};
	CBackground.prototype.put_Value = function (v)
	{
		this.Value = v;
	};

	window['Asc']['CBackground'] = window['Asc'].CBackground = CBackground;
	CBackground.prototype['get_Color'] = CBackground.prototype.get_Color;
	CBackground.prototype['put_Color'] = CBackground.prototype.put_Color;
	CBackground.prototype['get_Value'] = CBackground.prototype.get_Value;
	CBackground.prototype['put_Value'] = CBackground.prototype.put_Value;

// ---------------------------------------------------------------
	function CTablePositionH(obj)
	{
		if (obj)
		{
			this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? Asc.c_oAscHAnchor.Margin : obj.RelativeFrom;
			this.UseAlign = ( undefined === obj.UseAlign     ) ? false : obj.UseAlign;
			this.Align = ( undefined === obj.Align        ) ? undefined : obj.Align;
			this.Value = ( undefined === obj.Value        ) ? 0 : obj.Value;
		}
		else
		{
			this.RelativeFrom = Asc.c_oAscHAnchor.Column;
			this.UseAlign = false;
			this.Align = undefined;
			this.Value = 0;
		}
	}

	CTablePositionH.prototype.get_RelativeFrom = function ()
	{
		return this.RelativeFrom;
	};
	CTablePositionH.prototype.put_RelativeFrom = function (v)
	{
		this.RelativeFrom = v;
	};
	CTablePositionH.prototype.get_UseAlign = function ()
	{
		return this.UseAlign;
	};
	CTablePositionH.prototype.put_UseAlign = function (v)
	{
		this.UseAlign = v;
	};
	CTablePositionH.prototype.get_Align = function ()
	{
		return this.Align;
	};
	CTablePositionH.prototype.put_Align = function (v)
	{
		this.Align = v;
	};
	CTablePositionH.prototype.get_Value = function ()
	{
		return this.Value;
	};
	CTablePositionH.prototype.put_Value = function (v)
	{
		this.Value = v;
	};

	function CTablePositionV(obj)
	{
		if (obj)
		{
			this.RelativeFrom = ( undefined === obj.RelativeFrom ) ? Asc.c_oAscVAnchor.Text : obj.RelativeFrom;
			this.UseAlign = ( undefined === obj.UseAlign     ) ? false : obj.UseAlign;
			this.Align = ( undefined === obj.Align        ) ? undefined : obj.Align;
			this.Value = ( undefined === obj.Value        ) ? 0 : obj.Value;
		}
		else
		{
			this.RelativeFrom = Asc.c_oAscVAnchor.Text;
			this.UseAlign = false;
			this.Align = undefined;
			this.Value = 0;
		}
	}

	CTablePositionV.prototype.get_RelativeFrom = function ()
	{
		return this.RelativeFrom;
	};
	CTablePositionV.prototype.put_RelativeFrom = function (v)
	{
		this.RelativeFrom = v;
	};
	CTablePositionV.prototype.get_UseAlign = function ()
	{
		return this.UseAlign;
	};
	CTablePositionV.prototype.put_UseAlign = function (v)
	{
		this.UseAlign = v;
	};
	CTablePositionV.prototype.get_Align = function ()
	{
		return this.Align;
	};
	CTablePositionV.prototype.put_Align = function (v)
	{
		this.Align = v;
	};
	CTablePositionV.prototype.get_Value = function ()
	{
		return this.Value;
	};
	CTablePositionV.prototype.put_Value = function (v)
	{
		this.Value = v;
	};

	window['Asc']['CTablePositionH'] = CTablePositionH;
	CTablePositionH.prototype['get_RelativeFrom'] = CTablePositionH.prototype.get_RelativeFrom;
	CTablePositionH.prototype['put_RelativeFrom'] = CTablePositionH.prototype.put_RelativeFrom;
	CTablePositionH.prototype['get_UseAlign'] = CTablePositionH.prototype.get_UseAlign;
	CTablePositionH.prototype['put_UseAlign'] = CTablePositionH.prototype.put_UseAlign;
	CTablePositionH.prototype['get_Align'] = CTablePositionH.prototype.get_Align;
	CTablePositionH.prototype['put_Align'] = CTablePositionH.prototype.put_Align;
	CTablePositionH.prototype['get_Value'] = CTablePositionH.prototype.get_Value;
	CTablePositionH.prototype['put_Value'] = CTablePositionH.prototype.put_Value;
	window['Asc']['CTablePositionV'] = CTablePositionV;
	CTablePositionV.prototype['get_RelativeFrom'] = CTablePositionV.prototype.get_RelativeFrom;
	CTablePositionV.prototype['put_RelativeFrom'] = CTablePositionV.prototype.put_RelativeFrom;
	CTablePositionV.prototype['get_UseAlign'] = CTablePositionV.prototype.get_UseAlign;
	CTablePositionV.prototype['put_UseAlign'] = CTablePositionV.prototype.put_UseAlign;
	CTablePositionV.prototype['get_Align'] = CTablePositionV.prototype.get_Align;
	CTablePositionV.prototype['put_Align'] = CTablePositionV.prototype.put_Align;
	CTablePositionV.prototype['get_Value'] = CTablePositionV.prototype.get_Value;
	CTablePositionV.prototype['put_Value'] = CTablePositionV.prototype.put_Value;

// ---------------------------------------------------------------
	function CTablePropLook(obj)
	{
		this.FirstCol = false;
		this.FirstRow = false;
		this.LastCol = false;
		this.LastRow = false;
		this.BandHor = false;
		this.BandVer = false;

		if (obj)
		{
			this.FirstCol = ( undefined === obj.m_bFirst_Col ? false : obj.m_bFirst_Col );
			this.FirstRow = ( undefined === obj.m_bFirst_Row ? false : obj.m_bFirst_Row );
			this.LastCol = ( undefined === obj.m_bLast_Col ? false : obj.m_bLast_Col );
			this.LastRow = ( undefined === obj.m_bLast_Row ? false : obj.m_bLast_Row );
			this.BandHor = ( undefined === obj.m_bBand_Hor ? false : obj.m_bBand_Hor );
			this.BandVer = ( undefined === obj.m_bBand_Ver ? false : obj.m_bBand_Ver );
		}
	}

	CTablePropLook.prototype.get_FirstCol = function ()
	{
		return this.FirstCol;
	};
	CTablePropLook.prototype.put_FirstCol = function (v)
	{
		this.FirstCol = v;
	};
	CTablePropLook.prototype.get_FirstRow = function ()
	{
		return this.FirstRow;
	};
	CTablePropLook.prototype.put_FirstRow = function (v)
	{
		this.FirstRow = v;
	};
	CTablePropLook.prototype.get_LastCol = function ()
	{
		return this.LastCol;
	};
	CTablePropLook.prototype.put_LastCol = function (v)
	{
		this.LastCol = v;
	};
	CTablePropLook.prototype.get_LastRow = function ()
	{
		return this.LastRow;
	};
	CTablePropLook.prototype.put_LastRow = function (v)
	{
		this.LastRow = v;
	};
	CTablePropLook.prototype.get_BandHor = function ()
	{
		return this.BandHor;
	};
	CTablePropLook.prototype.put_BandHor = function (v)
	{
		this.BandHor = v;
	};
	CTablePropLook.prototype.get_BandVer = function ()
	{
		return this.BandVer;
	};
	CTablePropLook.prototype.put_BandVer = function (v)
	{
		this.BandVer = v;
	};

	window['Asc']['CTablePropLook'] = window['Asc'].CTablePropLook = CTablePropLook;
	CTablePropLook.prototype['get_FirstCol'] = CTablePropLook.prototype.get_FirstCol;
	CTablePropLook.prototype['put_FirstCol'] = CTablePropLook.prototype.put_FirstCol;
	CTablePropLook.prototype['get_FirstRow'] = CTablePropLook.prototype.get_FirstRow;
	CTablePropLook.prototype['put_FirstRow'] = CTablePropLook.prototype.put_FirstRow;
	CTablePropLook.prototype['get_LastCol'] = CTablePropLook.prototype.get_LastCol;
	CTablePropLook.prototype['put_LastCol'] = CTablePropLook.prototype.put_LastCol;
	CTablePropLook.prototype['get_LastRow'] = CTablePropLook.prototype.get_LastRow;
	CTablePropLook.prototype['put_LastRow'] = CTablePropLook.prototype.put_LastRow;
	CTablePropLook.prototype['get_BandHor'] = CTablePropLook.prototype.get_BandHor;
	CTablePropLook.prototype['put_BandHor'] = CTablePropLook.prototype.put_BandHor;
	CTablePropLook.prototype['get_BandVer'] = CTablePropLook.prototype.get_BandVer;
	CTablePropLook.prototype['put_BandVer'] = CTablePropLook.prototype.put_BandVer;

	/*
	 {
	 TableWidth   : null - галочка убрана, либо заданное значение в мм
	 TableSpacing : null - галочка убрана, либо заданное значение в мм

	 TableDefaultMargins :  // маргины для всей таблицы(значение по умолчанию)
	 {
	 Left   : 1.9,
	 Right  : 1.9,
	 Top    : 0,
	 Bottom : 0
	 }

	 CellMargins :
	 {
	 Left   : 1.9, (null - неопределенное значение)
	 Right  : 1.9, (null - неопределенное значение)
	 Top    : 0,   (null - неопределенное значение)
	 Bottom : 0,   (null - неопределенное значение)
	 Flag   : 0 - У всех выделенных ячеек значение берется из TableDefaultMargins
	 1 - У выделенных ячеек есть ячейки с дефолтовыми значениями, и есть со своими собственными
	 2 - У всех ячеек свои собственные значения
	 }

	 TableAlignment : 0, 1, 2 (слева, по центру, справа)
	 TableIndent : значение в мм,
	 TableWrappingStyle : 0, 1 (inline, flow)
	 TablePaddings:
	 {
	 Left   : 3.2,
	 Right  : 3.2,
	 Top    : 0,
	 Bottom : 0
	 }

	 TableBorders : // границы таблицы
	 {
	 Bottom :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Left :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Right :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Top :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 InsideH :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 InsideV :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 }
	 }

	 CellBorders : // границы выделенных ячеек
	 {
	 ForSelectedCells : true,

	 Bottom :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Left :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Right :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 Top :
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 InsideH : // данного элемента может не быть, если у выделенных ячеек
	 // нет горизонтальных внутренних границ
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 },

	 InsideV : // данного элемента может не быть, если у выделенных ячеек
	 // нет вертикальных внутренних границ
	 {
	 Color : { r : 0, g : 0, b : 0 },
	 Value : border_Single,
	 Size  : 0.5 * g_dKoef_pt_to_mm
	 Space :
	 }
	 }

	 TableBackground :
	 {
	 Value : тип заливки(прозрачная или нет),
	 Color : { r : 0, g : 0, b : 0 }
	 }
	 CellsBackground : null если заливка не определена для выделенных ячеек
	 {
	 Value : тип заливки(прозрачная или нет),
	 Color : { r : 0, g : 0, b : 0 }
	 }

	 Position:
	 {
	 X:0,
	 Y:0
	 }
	 }
	 */
	function CTableProp(tblProp)
	{
		if (tblProp)
		{
			this.CanBeFlow = (undefined != tblProp.CanBeFlow ? tblProp.CanBeFlow : false );
			this.CellSelect = (undefined != tblProp.CellSelect ? tblProp.CellSelect : false );
			this.CellSelect = (undefined != tblProp.CellSelect) ? tblProp.CellSelect : false;
			this.TableWidth = (undefined != tblProp.TableWidth) ? tblProp.TableWidth : null;
			this.TableSpacing = (undefined != tblProp.TableSpacing) ? tblProp.TableSpacing : null;
			this.TableDefaultMargins = (undefined != tblProp.TableDefaultMargins && null != tblProp.TableDefaultMargins) ? new Asc.asc_CPaddings(tblProp.TableDefaultMargins) : null;

			this.CellMargins = (undefined != tblProp.CellMargins && null != tblProp.CellMargins) ? new CMargins(tblProp.CellMargins) : null;

			this.TableAlignment = (undefined != tblProp.TableAlignment) ? tblProp.TableAlignment : null;
			this.TableIndent = (undefined != tblProp.TableIndent) ? tblProp.TableIndent : null;
			this.TableWrappingStyle = (undefined != tblProp.TableWrappingStyle) ? tblProp.TableWrappingStyle : null;

			this.TablePaddings = (undefined != tblProp.TablePaddings && null != tblProp.TablePaddings) ? new Asc.asc_CPaddings(tblProp.TablePaddings) : null;

			this.TableBorders = (undefined != tblProp.TableBorders && null != tblProp.TableBorders) ? new CBorders(tblProp.TableBorders) : null;
			this.CellBorders = (undefined != tblProp.CellBorders && null != tblProp.CellBorders) ? new CBorders(tblProp.CellBorders) : null;
			this.TableBackground = (undefined != tblProp.TableBackground && null != tblProp.TableBackground) ? new CBackground(tblProp.TableBackground) : null;
			this.CellsBackground = (undefined != tblProp.CellsBackground && null != tblProp.CellsBackground) ? new CBackground(tblProp.CellsBackground) : null;
			this.Position = (undefined != tblProp.Position && null != tblProp.Position) ? new Asc.CPosition(tblProp.Position) : null;
			this.PositionH = ( undefined != tblProp.PositionH && null != tblProp.PositionH ) ? new CTablePositionH(tblProp.PositionH) : undefined;
			this.PositionV = ( undefined != tblProp.PositionV && null != tblProp.PositionV ) ? new CTablePositionV(tblProp.PositionV) : undefined;
			this.Internal_Position = ( undefined != tblProp.Internal_Position ) ? tblProp.Internal_Position : undefined;

			this.ForSelectedCells = (undefined != tblProp.ForSelectedCells) ? tblProp.ForSelectedCells : true;
			this.TableStyle = (undefined != tblProp.TableStyle) ? tblProp.TableStyle : null;
			this.TableLook = (undefined != tblProp.TableLook) ? new CTablePropLook(tblProp.TableLook) : null;
			this.RowsInHeader = (undefined !== tblProp.RowsInHeader) ? tblProp.RowsInHeader : false;
			this.CellsVAlign = (undefined != tblProp.CellsVAlign) ? tblProp.CellsVAlign : c_oAscVertAlignJc.Top;
			this.AllowOverlap = (undefined != tblProp.AllowOverlap) ? tblProp.AllowOverlap : undefined;
			this.TableLayout = tblProp.TableLayout;
			this.CellsTextDirection = tblProp.CellsTextDirection;
			this.CellsNoWrap = tblProp.CellsNoWrap;
			this.CellsWidth = tblProp.CellsWidth;
			this.CellsWidthNotEqual = tblProp.CellsWidthNotEqual;
			this.Locked = (undefined != tblProp.Locked) ? tblProp.Locked : false;
			this.PercentFullWidth = tblProp.PercentFullWidth;
			this.TableDescription = tblProp.TableDescription;
			this.TableCaption = tblProp.TableCaption;

			this.ColumnWidth = tblProp.ColumnWidth;
			this.RowHeight   = tblProp.RowHeight;
		}
		else
		{
			//Все свойства класса CTableProp должны быть undefined если они не изменялись
			//this.CanBeFlow = false;
			this.CellSelect = false; //обязательное свойство
			/*this.TableWidth = null;
			 this.TableSpacing = null;
			 this.TableDefaultMargins = new Asc.asc_CPaddings ();

			 this.CellMargins = new CMargins ();

			 this.TableAlignment = 0;
			 this.TableIndent = 0;
			 this.TableWrappingStyle = c_oAscWrapStyle.Inline;

			 this.TablePaddings = new Asc.asc_CPaddings ();

			 this.TableBorders = new CBorders ();
			 this.CellBorders = new CBorders ();
			 this.TableBackground = new CBackground ();
			 this.CellsBackground = new CBackground ();;
			 this.Position = new CPosition ();
			 this.ForSelectedCells = true;*/

			this.Locked = false;
		}
	}

	CTableProp.prototype.get_Width = function ()
	{
		return this.TableWidth;
	};
	CTableProp.prototype.put_Width = function (v)
	{
		this.TableWidth = v;
	};
	CTableProp.prototype.get_Spacing = function ()
	{
		return this.TableSpacing;
	};
	CTableProp.prototype.put_Spacing = function (v)
	{
		this.TableSpacing = v;
	};
	CTableProp.prototype.get_DefaultMargins = function ()
	{
		return this.TableDefaultMargins;
	};
	CTableProp.prototype.put_DefaultMargins = function (v)
	{
		this.TableDefaultMargins = v;
	};
	CTableProp.prototype.get_CellMargins = function ()
	{
		return this.CellMargins;
	};
	CTableProp.prototype.put_CellMargins = function (v)
	{
		this.CellMargins = v;
	};
	CTableProp.prototype.get_TableAlignment = function ()
	{
		return this.TableAlignment;
	};
	CTableProp.prototype.put_TableAlignment = function (v)
	{
		this.TableAlignment = v;
	};
	CTableProp.prototype.get_TableIndent = function ()
	{
		return this.TableIndent;
	};
	CTableProp.prototype.put_TableIndent = function (v)
	{
		this.TableIndent = v;
	};
	CTableProp.prototype.get_TableWrap = function ()
	{
		return this.TableWrappingStyle;
	};
	CTableProp.prototype.put_TableWrap = function (v)
	{
		this.TableWrappingStyle = v;
	};
	CTableProp.prototype.get_TablePaddings = function ()
	{
		return this.TablePaddings;
	};
	CTableProp.prototype.put_TablePaddings = function (v)
	{
		this.TablePaddings = v;
	};
	CTableProp.prototype.get_TableBorders = function ()
	{
		return this.TableBorders;
	};
	CTableProp.prototype.put_TableBorders = function (v)
	{
		this.TableBorders = v;
	};
	CTableProp.prototype.get_CellBorders = function ()
	{
		return this.CellBorders;
	};
	CTableProp.prototype.put_CellBorders = function (v)
	{
		this.CellBorders = v;
	};
	CTableProp.prototype.get_TableBackground = function ()
	{
		return this.TableBackground;
	};
	CTableProp.prototype.put_TableBackground = function (v)
	{
		this.TableBackground = v;
	};
	CTableProp.prototype.get_CellsBackground = function ()
	{
		return this.CellsBackground;
	};
	CTableProp.prototype.put_CellsBackground = function (v)
	{
		this.CellsBackground = v;
	};
	CTableProp.prototype.get_Position = function ()
	{
		return this.Position;
	};
	CTableProp.prototype.put_Position = function (v)
	{
		this.Position = v;
	};
	CTableProp.prototype.get_PositionH = function ()
	{
		return this.PositionH;
	};
	CTableProp.prototype.put_PositionH = function (v)
	{
		this.PositionH = v;
	};
	CTableProp.prototype.get_PositionV = function ()
	{
		return this.PositionV;
	};
	CTableProp.prototype.put_PositionV = function (v)
	{
		this.PositionV = v;
	};
	CTableProp.prototype.get_Value_X = function (RelativeFrom)
	{
		if (undefined != this.Internal_Position) return this.Internal_Position.Calculate_X_Value(RelativeFrom);
		return 0;
	};
	CTableProp.prototype.get_Value_Y = function (RelativeFrom)
	{
		if (undefined != this.Internal_Position) return this.Internal_Position.Calculate_Y_Value(RelativeFrom);
		return 0;
	};
	CTableProp.prototype.get_ForSelectedCells = function ()
	{
		return this.ForSelectedCells;
	};
	CTableProp.prototype.put_ForSelectedCells = function (v)
	{
		this.ForSelectedCells = v;
	};
	CTableProp.prototype.put_CellSelect = function (v)
	{
		this.CellSelect = v;
	};
	CTableProp.prototype.get_CellSelect = function ()
	{
		return this.CellSelect
	};
	CTableProp.prototype.get_CanBeFlow = function ()
	{
		return this.CanBeFlow;
	};
	CTableProp.prototype.get_RowsInHeader = function ()
	{
		return this.RowsInHeader;
	};
	CTableProp.prototype.put_RowsInHeader = function (v)
	{
		this.RowsInHeader = v;
	};
	CTableProp.prototype.get_Locked = function ()
	{
		return this.Locked;
	};
	CTableProp.prototype.get_CellsVAlign = function ()
	{
		return this.CellsVAlign;
	};
	CTableProp.prototype.put_CellsVAlign = function (v)
	{
		this.CellsVAlign = v;
	};
	CTableProp.prototype.get_TableLook = function ()
	{
		return this.TableLook;
	};
	CTableProp.prototype.put_TableLook = function (v)
	{
		this.TableLook = v;
	};
	CTableProp.prototype.get_TableStyle = function ()
	{
		return this.TableStyle;
	};
	CTableProp.prototype.put_TableStyle = function (v)
	{
		this.TableStyle = v;
	};
	CTableProp.prototype.get_AllowOverlap = function ()
	{
		return this.AllowOverlap;
	};
	CTableProp.prototype.put_AllowOverlap = function (v)
	{
		this.AllowOverlap = v;
	};
	CTableProp.prototype.get_TableLayout = function ()
	{
		return this.TableLayout;
	};
	CTableProp.prototype.put_TableLayout = function (v)
	{
		this.TableLayout = v;
	};
	CTableProp.prototype.get_CellsTextDirection = function ()
	{
		return this.CellsTextDirection;
	};
	CTableProp.prototype.put_CellsTextDirection = function (v)
	{
		this.CellsTextDirection = v;
	};
	CTableProp.prototype.get_CellsNoWrap = function ()
	{
		return this.CellsNoWrap;
	};
	CTableProp.prototype.put_CellsNoWrap = function (v)
	{
		this.CellsNoWrap = v;
	};
	CTableProp.prototype.get_CellsWidth = function ()
	{
		return this.CellsWidth;
	};
	CTableProp.prototype.put_CellsWidth = function (v)
	{
		this.CellsWidth = v;
	};
	CTableProp.prototype.get_PercentFullWidth = function ()
	{
		return this.PercentFullWidth;
	};
	CTableProp.prototype.get_CellsWidthNotEqual = function ()
	{
		return this.CellsWidthNotEqual;
	};
	CTableProp.prototype.get_TableDescription = function ()
	{
		return this.TableDescription;
	};
	CTableProp.prototype.put_TableDescription = function (v)
	{
		this.TableDescription = v;
	};
	CTableProp.prototype.get_TableCaption = function ()
	{
		return this.TableCaption;
	};
	CTableProp.prototype.put_TableCaption = function (v)
	{
		this.TableCaption = v;
	};
	CTableProp.prototype.get_ColumnWidth = function()
	{
		return this.ColumnWidth;
	};
	CTableProp.prototype.put_ColumnWidth = function(v)
	{
		this.ColumnWidth = v;
	};
	CTableProp.prototype.get_RowHeight = function()
	{
		return this.RowHeight;
	};
	CTableProp.prototype.put_RowHeight = function(v)
	{
		this.RowHeight = v;
	};

	window['Asc']['CTableProp'] = window['Asc'].CTableProp = CTableProp;
	CTableProp.prototype['get_Width'] = CTableProp.prototype.get_Width;
	CTableProp.prototype['put_Width'] = CTableProp.prototype.put_Width;
	CTableProp.prototype['get_Spacing'] = CTableProp.prototype.get_Spacing;
	CTableProp.prototype['put_Spacing'] = CTableProp.prototype.put_Spacing;
	CTableProp.prototype['get_DefaultMargins'] = CTableProp.prototype.get_DefaultMargins;
	CTableProp.prototype['put_DefaultMargins'] = CTableProp.prototype.put_DefaultMargins;
	CTableProp.prototype['get_CellMargins'] = CTableProp.prototype.get_CellMargins;
	CTableProp.prototype['put_CellMargins'] = CTableProp.prototype.put_CellMargins;
	CTableProp.prototype['get_TableAlignment'] = CTableProp.prototype.get_TableAlignment;
	CTableProp.prototype['put_TableAlignment'] = CTableProp.prototype.put_TableAlignment;
	CTableProp.prototype['get_TableIndent'] = CTableProp.prototype.get_TableIndent;
	CTableProp.prototype['put_TableIndent'] = CTableProp.prototype.put_TableIndent;
	CTableProp.prototype['get_TableWrap'] = CTableProp.prototype.get_TableWrap;
	CTableProp.prototype['put_TableWrap'] = CTableProp.prototype.put_TableWrap;
	CTableProp.prototype['get_TablePaddings'] = CTableProp.prototype.get_TablePaddings;
	CTableProp.prototype['put_TablePaddings'] = CTableProp.prototype.put_TablePaddings;
	CTableProp.prototype['get_TableBorders'] = CTableProp.prototype.get_TableBorders;
	CTableProp.prototype['put_TableBorders'] = CTableProp.prototype.put_TableBorders;
	CTableProp.prototype['get_CellBorders'] = CTableProp.prototype.get_CellBorders;
	CTableProp.prototype['put_CellBorders'] = CTableProp.prototype.put_CellBorders;
	CTableProp.prototype['get_TableBackground'] = CTableProp.prototype.get_TableBackground;
	CTableProp.prototype['put_TableBackground'] = CTableProp.prototype.put_TableBackground;
	CTableProp.prototype['get_CellsBackground'] = CTableProp.prototype.get_CellsBackground;
	CTableProp.prototype['put_CellsBackground'] = CTableProp.prototype.put_CellsBackground;
	CTableProp.prototype['get_Position'] = CTableProp.prototype.get_Position;
	CTableProp.prototype['put_Position'] = CTableProp.prototype.put_Position;
	CTableProp.prototype['get_PositionH'] = CTableProp.prototype.get_PositionH;
	CTableProp.prototype['put_PositionH'] = CTableProp.prototype.put_PositionH;
	CTableProp.prototype['get_PositionV'] = CTableProp.prototype.get_PositionV;
	CTableProp.prototype['put_PositionV'] = CTableProp.prototype.put_PositionV;
	CTableProp.prototype['get_Value_X'] = CTableProp.prototype.get_Value_X;
	CTableProp.prototype['get_Value_Y'] = CTableProp.prototype.get_Value_Y;
	CTableProp.prototype['get_ForSelectedCells'] = CTableProp.prototype.get_ForSelectedCells;
	CTableProp.prototype['put_ForSelectedCells'] = CTableProp.prototype.put_ForSelectedCells;
	CTableProp.prototype['put_CellSelect'] = CTableProp.prototype.put_CellSelect;
	CTableProp.prototype['get_CellSelect'] = CTableProp.prototype.get_CellSelect;
	CTableProp.prototype['get_CanBeFlow'] = CTableProp.prototype.get_CanBeFlow;
	CTableProp.prototype['get_RowsInHeader'] = CTableProp.prototype.get_RowsInHeader;
	CTableProp.prototype['put_RowsInHeader'] = CTableProp.prototype.put_RowsInHeader;
	CTableProp.prototype['get_Locked'] = CTableProp.prototype.get_Locked;
	CTableProp.prototype['get_CellsVAlign'] = CTableProp.prototype.get_CellsVAlign;
	CTableProp.prototype['put_CellsVAlign'] = CTableProp.prototype.put_CellsVAlign;
	CTableProp.prototype['get_TableLook'] = CTableProp.prototype.get_TableLook;
	CTableProp.prototype['put_TableLook'] = CTableProp.prototype.put_TableLook;
	CTableProp.prototype['get_TableStyle'] = CTableProp.prototype.get_TableStyle;
	CTableProp.prototype['put_TableStyle'] = CTableProp.prototype.put_TableStyle;
	CTableProp.prototype['get_AllowOverlap'] = CTableProp.prototype.get_AllowOverlap;
	CTableProp.prototype['put_AllowOverlap'] = CTableProp.prototype.put_AllowOverlap;
	CTableProp.prototype['get_TableLayout'] = CTableProp.prototype.get_TableLayout;
	CTableProp.prototype['put_TableLayout'] = CTableProp.prototype.put_TableLayout;
	CTableProp.prototype['get_CellsTextDirection'] = CTableProp.prototype.get_CellsTextDirection;
	CTableProp.prototype['put_CellsTextDirection'] = CTableProp.prototype.put_CellsTextDirection;
	CTableProp.prototype['get_CellsNoWrap'] = CTableProp.prototype.get_CellsNoWrap;
	CTableProp.prototype['put_CellsNoWrap'] = CTableProp.prototype.put_CellsNoWrap;
	CTableProp.prototype['get_CellsWidth'] = CTableProp.prototype.get_CellsWidth;
	CTableProp.prototype['put_CellsWidth'] = CTableProp.prototype.put_CellsWidth;
	CTableProp.prototype['get_PercentFullWidth'] = CTableProp.prototype.get_PercentFullWidth;
	CTableProp.prototype['get_CellsWidthNotEqual'] = CTableProp.prototype.get_CellsWidthNotEqual;
	CTableProp.prototype['get_TableDescription'] = CTableProp.prototype.get_TableDescription;
	CTableProp.prototype['put_TableDescription'] = CTableProp.prototype.put_TableDescription;
	CTableProp.prototype['get_TableCaption'] = CTableProp.prototype.get_TableCaption;
	CTableProp.prototype['put_TableCaption'] = CTableProp.prototype.put_TableCaption;
	CTableProp.prototype['get_ColumnWidth'] = CTableProp.prototype.get_ColumnWidth;
	CTableProp.prototype['put_ColumnWidth'] = CTableProp.prototype.put_ColumnWidth;
	CTableProp.prototype['get_RowHeight'] = CTableProp.prototype.get_RowHeight;
	CTableProp.prototype['put_RowHeight'] = CTableProp.prototype.put_RowHeight;

// ---------------------------------------------------------------
	function CBorders(obj)
	{
		if (obj)
		{
			this.Left = (undefined != obj.Left && null != obj.Left) ? new Asc.asc_CTextBorder(obj.Left) : null;
			this.Top = (undefined != obj.Top && null != obj.Top) ? new Asc.asc_CTextBorder(obj.Top) : null;
			this.Right = (undefined != obj.Right && null != obj.Right) ? new Asc.asc_CTextBorder(obj.Right) : null;
			this.Bottom = (undefined != obj.Bottom && null != obj.Bottom) ? new Asc.asc_CTextBorder(obj.Bottom) : null;
			this.InsideH = (undefined != obj.InsideH && null != obj.InsideH) ? new Asc.asc_CTextBorder(obj.InsideH) : null;
			this.InsideV = (undefined != obj.InsideV && null != obj.InsideV) ? new Asc.asc_CTextBorder(obj.InsideV) : null;
		}
		//Все свойства класса CBorders должны быть undefined если они не изменялись
		/*else
		 {
		 this.Left = null;
		 this.Top = null;
		 this.Right = null;
		 this.Bottom = null;
		 this.InsideH = null;
		 this.InsideV = null;
		 }*/
	}

	CBorders.prototype.get_Left = function ()
	{
		return this.Left;
	};
	CBorders.prototype.put_Left = function (v)
	{
		this.Left = (v) ? new Asc.asc_CTextBorder(v) : null;
	};
	CBorders.prototype.get_Top = function ()
	{
		return this.Top;
	};
	CBorders.prototype.put_Top = function (v)
	{
		this.Top = (v) ? new Asc.asc_CTextBorder(v) : null;
	};
	CBorders.prototype.get_Right = function ()
	{
		return this.Right;
	};
	CBorders.prototype.put_Right = function (v)
	{
		this.Right = (v) ? new Asc.asc_CTextBorder(v) : null;
	};
	CBorders.prototype.get_Bottom = function ()
	{
		return this.Bottom;
	};
	CBorders.prototype.put_Bottom = function (v)
	{
		this.Bottom = (v) ? new Asc.asc_CTextBorder(v) : null;
	};
	CBorders.prototype.get_InsideH = function ()
	{
		return this.InsideH;
	};
	CBorders.prototype.put_InsideH = function (v)
	{
		this.InsideH = (v) ? new Asc.asc_CTextBorder(v) : null;
	};
	CBorders.prototype.get_InsideV = function ()
	{
		return this.InsideV;
	};
	CBorders.prototype.put_InsideV = function (v)
	{
		this.InsideV = (v) ? new Asc.asc_CTextBorder(v) : null;
	};

	function CMargins(obj)
	{
		if (obj)
		{
			this.Left = (undefined != obj.Left) ? obj.Left : null;
			this.Right = (undefined != obj.Right) ? obj.Right : null;
			this.Top = (undefined != obj.Top) ? obj.Top : null;
			this.Bottom = (undefined != obj.Bottom) ? obj.Bottom : null;
			this.Flag = (undefined != obj.Flag) ? obj.Flag : null;
		}
		else
		{
			this.Left = null;
			this.Right = null;
			this.Top = null;
			this.Bottom = null;
			this.Flag = null;
		}
	}

	CMargins.prototype.get_Left = function ()
	{
		return this.Left;
	};
	CMargins.prototype.put_Left = function (v)
	{
		this.Left = v;
	};
	CMargins.prototype.get_Right = function ()
	{
		return this.Right;
	};
	CMargins.prototype.put_Right = function (v)
	{
		this.Right = v;
	};
	CMargins.prototype.get_Top = function ()
	{
		return this.Top;
	};
	CMargins.prototype.put_Top = function (v)
	{
		this.Top = v;
	};
	CMargins.prototype.get_Bottom = function ()
	{
		return this.Bottom;
	};
	CMargins.prototype.put_Bottom = function (v)
	{
		this.Bottom = v;
	};
	CMargins.prototype.get_Flag = function ()
	{
		return this.Flag;
	};
	CMargins.prototype.put_Flag = function (v)
	{
		this.Flag = v;
	};

	window['Asc']['CBorders'] = window['Asc'].CBorders = CBorders;
	CBorders.prototype['get_Left'] = CBorders.prototype.get_Left;
	CBorders.prototype['put_Left'] = CBorders.prototype.put_Left;
	CBorders.prototype['get_Top'] = CBorders.prototype.get_Top;
	CBorders.prototype['put_Top'] = CBorders.prototype.put_Top;
	CBorders.prototype['get_Right'] = CBorders.prototype.get_Right;
	CBorders.prototype['put_Right'] = CBorders.prototype.put_Right;
	CBorders.prototype['get_Bottom'] = CBorders.prototype.get_Bottom;
	CBorders.prototype['put_Bottom'] = CBorders.prototype.put_Bottom;
	CBorders.prototype['get_InsideH'] = CBorders.prototype.get_InsideH;
	CBorders.prototype['put_InsideH'] = CBorders.prototype.put_InsideH;
	CBorders.prototype['get_InsideV'] = CBorders.prototype.get_InsideV;
	CBorders.prototype['put_InsideV'] = CBorders.prototype.put_InsideV;
	window['Asc']['CMargins'] = window['Asc'].CMargins = CMargins;
	CMargins.prototype['get_Left'] = CMargins.prototype.get_Left;
	CMargins.prototype['put_Left'] = CMargins.prototype.put_Left;
	CMargins.prototype['get_Right'] = CMargins.prototype.get_Right;
	CMargins.prototype['put_Right'] = CMargins.prototype.put_Right;
	CMargins.prototype['get_Top'] = CMargins.prototype.get_Top;
	CMargins.prototype['put_Top'] = CMargins.prototype.put_Top;
	CMargins.prototype['get_Bottom'] = CMargins.prototype.get_Bottom;
	CMargins.prototype['put_Bottom'] = CMargins.prototype.put_Bottom;
	CMargins.prototype['get_Flag'] = CMargins.prototype.get_Flag;
	CMargins.prototype['put_Flag'] = CMargins.prototype.put_Flag;

// ---------------------------------------------------------------
	function CParagraphPropEx(obj)
	{
		if (obj)
		{
			this.ContextualSpacing = (undefined != obj.ContextualSpacing) ? obj.ContextualSpacing : null;
			this.Ind = (undefined != obj.Ind && null != obj.Ind) ? new Asc.asc_CParagraphInd(obj.Ind) : null;
			this.Jc = (undefined != obj.Jc) ? obj.Jc : null;
			this.KeepLines = (undefined != obj.KeepLines) ? obj.KeepLines : null;
			this.KeepNext = (undefined != obj.KeepNext) ? obj.KeepNext : null;
			this.PageBreakBefore = (undefined != obj.PageBreakBefore) ? obj.PageBreakBefore : null;
			this.Spacing = (undefined != obj.Spacing && null != obj.Spacing) ? new AscCommon.asc_CParagraphSpacing(obj.Spacing) : null;
			this.Shd = (undefined != obj.Shd && null != obj.Shd) ? new Asc.asc_CParagraphShd(obj.Shd) : null;
			this.WidowControl = (undefined != obj.WidowControl) ? obj.WidowControl : null;                  // Запрет висячих строк
			this.Tabs = obj.Tabs;
		}
		else
		{
			//ContextualSpacing : false,            // Удалять ли интервал между параграфами одинакового стиля
			//
			//    Ind :
			//    {
			//        Left      : 0,                    // Левый отступ
			//        Right     : 0,                    // Правый отступ
			//        FirstLine : 0                     // Первая строка
			//    },
			//
			//    Jc : align_Left,                      // Прилегание параграфа
			//
			//    KeepLines : false,                    // переносить параграф на новую страницу,
			//                                          // если на текущей он целиком не убирается
			//    KeepNext  : false,                    // переносить параграф вместе со следующим параграфом
			//
			//    PageBreakBefore : false,              // начинать параграф с новой страницы
			//    Spacing :
			//    {
			//        Line     : 1.15,                  // Расстояние между строками внутри абзаца
			//        LineRule : linerule_Auto,         // Тип расстрояния между строками
			//        Before   : 0,                     // Дополнительное расстояние до абзаца
			//        After    : 10 * g_dKoef_pt_to_mm  // Дополнительное расстояние после абзаца
			//    },
			//
			//    Shd :
			//    {
			//        Value : shd_Nil,
			//        Color :
			//        {
			//            r : 255,
			//            g : 255,
			//            b : 255
			//        }
			//    },
			//
			//    WidowControl : true,                  // Запрет висячих строк
			//
			//    Tabs : []
			this.ContextualSpacing = false;
			this.Ind = new Asc.asc_CParagraphInd();
			this.Jc = AscCommon.align_Left;
			this.KeepLines = false;
			this.KeepNext = false;
			this.PageBreakBefore = false;
			this.Spacing = new AscCommon.asc_CParagraphSpacing();
			this.Shd = new Asc.asc_CParagraphShd();
			this.WidowControl = true;                  // Запрет висячих строк
			this.Tabs = null;
		}
	}

	CParagraphPropEx.prototype.get_ContextualSpacing = function ()
	{
		return this.ContextualSpacing;
	};
	CParagraphPropEx.prototype.get_Ind = function ()
	{
		return this.Ind;
	};
	CParagraphPropEx.prototype.get_Jc = function ()
	{
		return this.Jc;
	};
	CParagraphPropEx.prototype.get_KeepLines = function ()
	{
		return this.KeepLines;
	};
	CParagraphPropEx.prototype.get_KeepNext = function ()
	{
		return this.KeepNext;
	};
	CParagraphPropEx.prototype.get_PageBreakBefore = function ()
	{
		return this.PageBreakBefore;
	};
	CParagraphPropEx.prototype.get_Spacing = function ()
	{
		return this.Spacing;
	};
	CParagraphPropEx.prototype.get_Shd = function ()
	{
		return this.Shd;
	};
	CParagraphPropEx.prototype.get_WidowControl = function ()
	{
		return this.WidowControl;
	};
	CParagraphPropEx.prototype.get_Tabs = function ()
	{
		return this.Tabs;
	};

	function CTextProp(obj)
	{
		if (obj)
		{
			this.Bold = (undefined != obj.Bold) ? obj.Bold : null;
			this.Italic = (undefined != obj.Italic) ? obj.Italic : null;
			this.Underline = (undefined != obj.Underline) ? obj.Underline : null;
			this.Strikeout = (undefined != obj.Strikeout) ? obj.Strikeout : null;
			this.FontFamily = (undefined != obj.FontFamily && null != obj.FontFamily) ? new AscCommon.asc_CTextFontFamily(obj.FontFamily) : new AscCommon.asc_CTextFontFamily({Name : "", Index : -1});
			this.FontSize = (undefined != obj.FontSize) ? obj.FontSize : null;
			this.Color = (undefined != obj.Color && null != obj.Color) ? AscCommon.CreateAscColorCustom(obj.Color.r, obj.Color.g, obj.Color.b) : null;
			this.VertAlign = (undefined != obj.VertAlign) ? obj.VertAlign : null;
			this.HighLight = (undefined != obj.HighLight) ? obj.HighLight == AscCommonWord.highlight_None ? obj.HighLight : new AscCommon.CColor(obj.HighLight.r, obj.HighLight.g, obj.HighLight.b) : null;
			this.DStrikeout = (undefined != obj.DStrikeout) ? obj.DStrikeout : null;
			this.Spacing = (undefined != obj.Spacing) ? obj.Spacing : null;
			this.Caps = (undefined != obj.Caps) ? obj.Caps : null;
			this.SmallCaps = (undefined != obj.SmallCaps) ? obj.SmallCaps : null;
		}
		else
		{
			//    Bold       : false,
			//    Italic     : false,
			//    Underline  : false,
			//    Strikeout  : false,
			//    FontFamily :
			//    {
			//        Name  : "Times New Roman",
			//        Index : -1
			//    },
			//    FontSize   : 12,
			//    Color      :
			//    {
			//        r : 0,
			//        g : 0,
			//        b : 0
			//    },
			//    VertAlign : vertalign_Baseline,
			//    HighLight : highlight_None
			this.Bold = false;
			this.Italic = false;
			this.Underline = false;
			this.Strikeout = false;
			this.FontFamily = new AscCommon.asc_CTextFontFamily();
			this.FontSize = 12;
			this.Color = AscCommon.CreateAscColorCustom(0, 0, 0);
			this.VertAlign = AscCommon.vertalign_Baseline;
			this.HighLight = AscCommonWord.highlight_None;
			this.DStrikeout = false;
			this.Spacing = 0;
			this.Caps = false;
			this.SmallCaps = false;
		}
	}

	CTextProp.prototype.get_Bold = function ()
	{
		return this.Bold;
	};
	CTextProp.prototype.get_Italic = function ()
	{
		return this.Italic;
	};
	CTextProp.prototype.get_Underline = function ()
	{
		return this.Underline;
	};
	CTextProp.prototype.get_Strikeout = function ()
	{
		return this.Strikeout;
	};
	CTextProp.prototype.get_FontFamily = function ()
	{
		return this.FontFamily;
	};
	CTextProp.prototype.get_FontSize = function ()
	{
		return this.FontSize;
	};
	CTextProp.prototype.get_Color = function ()
	{
		return this.Color;
	};
	CTextProp.prototype.get_VertAlign = function ()
	{
		return this.VertAlign;
	};
	CTextProp.prototype.get_HighLight = function ()
	{
		return this.HighLight;
	};
	CTextProp.prototype.get_Spacing = function ()
	{
		return this.Spacing;
	};
	CTextProp.prototype.get_DStrikeout = function ()
	{
		return this.DStrikeout;
	};
	CTextProp.prototype.get_Caps = function ()
	{
		return this.Caps;
	};
	CTextProp.prototype.get_SmallCaps = function ()
	{
		return this.SmallCaps;
	};

	CParagraphPropEx.prototype['get_ContextualSpacing'] = CParagraphPropEx.prototype.get_ContextualSpacing;
	CParagraphPropEx.prototype['get_Ind'] = CParagraphPropEx.prototype.get_Ind;
	CParagraphPropEx.prototype['get_Jc'] = CParagraphPropEx.prototype.get_Jc;
	CParagraphPropEx.prototype['get_KeepLines'] = CParagraphPropEx.prototype.get_KeepLines;
	CParagraphPropEx.prototype['get_KeepNext'] = CParagraphPropEx.prototype.get_KeepNext;
	CParagraphPropEx.prototype['get_PageBreakBefore'] = CParagraphPropEx.prototype.get_PageBreakBefore;
	CParagraphPropEx.prototype['get_Spacing'] = CParagraphPropEx.prototype.get_Spacing;
	CParagraphPropEx.prototype['get_Shd'] = CParagraphPropEx.prototype.get_Shd;
	CParagraphPropEx.prototype['get_WidowControl'] = CParagraphPropEx.prototype.get_WidowControl;
	CParagraphPropEx.prototype['get_Tabs'] = CParagraphPropEx.prototype.get_Tabs;
	CTextProp.prototype['get_Bold'] = CTextProp.prototype.get_Bold;
	CTextProp.prototype['get_Italic'] = CTextProp.prototype.get_Italic;
	CTextProp.prototype['get_Underline'] = CTextProp.prototype.get_Underline;
	CTextProp.prototype['get_Strikeout'] = CTextProp.prototype.get_Strikeout;
	CTextProp.prototype['get_FontFamily'] = CTextProp.prototype.get_FontFamily;
	CTextProp.prototype['get_FontSize'] = CTextProp.prototype.get_FontSize;
	CTextProp.prototype['get_Color'] = CTextProp.prototype.get_Color;
	CTextProp.prototype['get_VertAlign'] = CTextProp.prototype.get_VertAlign;
	CTextProp.prototype['get_HighLight'] = CTextProp.prototype.get_HighLight;
	CTextProp.prototype['get_Spacing'] = CTextProp.prototype.get_Spacing;
	CTextProp.prototype['get_DStrikeout'] = CTextProp.prototype.get_DStrikeout;
	CTextProp.prototype['get_Caps'] = CTextProp.prototype.get_Caps;
	CTextProp.prototype['get_SmallCaps'] = CTextProp.prototype.get_SmallCaps;

	/**
	 * Paragraph and text properties objects container
	 * @param paragraphProp
	 * @param textProp
	 * @constructor
	 */
	function CParagraphAndTextProp(paragraphProp, textProp)
	{
		this.ParaPr = (undefined != paragraphProp && null != paragraphProp) ? new CParagraphPropEx(paragraphProp) : null;
		this.TextPr = (undefined != textProp && null != textProp) ? new CTextProp(textProp) : null;
	}

	/**
	 * @returns {?CParagraphPropEx}
	 */
	CParagraphAndTextProp.prototype.get_ParaPr = function ()
	{
		return this.ParaPr;
	};
	/**
	 * @returns {?CTextProp}
	 */
	CParagraphAndTextProp.prototype.get_TextPr = function ()
	{
		return this.TextPr;
	};

	window['Asc']['CParagraphAndTextProp'] = window['Asc'].CParagraphAndTextProp = CParagraphAndTextProp;
	CParagraphAndTextProp.prototype['get_ParaPr'] = CParagraphAndTextProp.prototype.get_ParaPr;
	CParagraphAndTextProp.prototype['get_TextPr'] = CParagraphAndTextProp.prototype.get_TextPr;
// ---------------------------------------------------------------

	function GenerateTableStyles(drawingDoc, logicDoc, tableLook)
	{
		var _dst_styles = [];

		var _styles = logicDoc.Styles.Get_AllTableStyles();
		var _styles_len = _styles.length;

		if (_styles_len == 0)
			return _dst_styles;

		var _x_mar = 10;
		var _y_mar = 10;
		var _r_mar = 10;
		var _b_mar = 10;
		var _pageW = 297;
		var _pageH = 210;

		var W = (_pageW - _x_mar - _r_mar);
		var H = (_pageH - _y_mar - _b_mar);
		var Grid = [];

		var Rows = 5;
		var Cols = 5;

		for (var i = 0; i < Cols; i++)
			Grid[i] = W / Cols;

		var _canvas = document.createElement('canvas');
		if (!this.m_oWordControl.bIsRetinaSupport)
		{
			_canvas.width = TABLE_STYLE_WIDTH_PIX;
			_canvas.height = TABLE_STYLE_HEIGHT_PIX;
		}
		else
		{
			_canvas.width = AscCommon.AscBrowser.convertToRetinaValue(TABLE_STYLE_WIDTH_PIX, true);
			_canvas.height = AscCommon.AscBrowser.convertToRetinaValue(TABLE_STYLE_HEIGHT_PIX, true);
		}
		var ctx = _canvas.getContext('2d');

		AscCommon.History.TurnOff();
		for (var i1 = 0; i1 < _styles_len; i1++)
		{
			var i = _styles[i1];
			var _style = logicDoc.Styles.Style[i];

			if (!_style || _style.Type != styletype_Table)
				continue;

			var table = new CTable(drawingDoc, logicDoc, true, Rows, Cols, Grid);
			table.Set_Props({TableStyle: i});

			for (var j = 0; j < Rows; j++)
				table.Content[j].Set_Height(H / Rows, Asc.linerule_AtLeast);

			ctx.fillStyle = "#FFFFFF";
			ctx.fillRect(0, 0, _canvas.width, _canvas.height);

			var graphics = new AscCommon.CGraphics();
			graphics.init(ctx, _canvas.width, _canvas.height, _pageW, _pageH);
			graphics.m_oFontManager = AscCommon.g_fontManager;
			graphics.transform(1, 0, 0, 1, 0, 0);

			table.Reset(_x_mar, _y_mar, 1000, 1000, 0, 0, 1);
			table.Recalculate_Page(0);
			table.Draw(0, graphics);

			var _styleD = new CAscTableStyle();
			_styleD.Type = 0;
			_styleD.Image = _canvas.toDataURL("image/png");
			_styleD.Id = i;
			_dst_styles.push(_styleD);
		}
		AscCommon.History.TurnOn();

		return _dst_styles;
	}

	/*
	 структура заголовков, предварительно, выглядит так
	 {
	 headerText: "Header1",//заголовок
	 pageNumber: 0, //содержит номер страницы, где находится искомая последовательность
	 X: 0,//координаты по OX начала последовательности на данной страницы
	 Y: 0,//координаты по OY начала последовательности на данной страницы
	 level: 0//уровень заголовка
	 }
	 заголовки приходят либо в списке, либо последовательно.
	 */

	function CHeader(obj)
	{
		if (obj)
		{
			this.headerText = (undefined != obj.headerText) ? obj.headerText : null;	//заголовок
			this.pageNumber = (undefined != obj.pageNumber) ? obj.pageNumber : null;	//содержит номер страницы, где находится искомая последовательность
			this.X = (undefined != obj.X) ? obj.X : null;						//координаты по OX начала последовательности на данной страницы
			this.Y = (undefined != obj.Y) ? obj.Y : null;						//координаты по OY начала последовательности на данной страницы
			this.level = (undefined != obj.level) ? obj.level : null;				//позиция заголовка
		}
		else
		{
			this.headerText = null;				//заголовок
			this.pageNumber = null;				//содержит номер страницы, где находится искомая последовательность
			this.X = null;				//координаты по OX начала последовательности на данной страницы
			this.Y = null;				//координаты по OY начала последовательности на данной страницы
			this.level = null;				//позиция заголовка
		}
	}

	CHeader.prototype.get_headerText = function ()
	{
		return this.headerText;
	};
	CHeader.prototype.get_pageNumber = function ()
	{
		return this.pageNumber;
	};
	CHeader.prototype.get_X = function ()
	{
		return this.X;
	};
	CHeader.prototype.get_Y = function ()
	{
		return this.Y;
	};
	CHeader.prototype.get_Level = function ()
	{
		return this.level;
	};

	window['Asc']['CHeader'] = window['Asc'].CHeader = CHeader;
	CHeader.prototype['get_headerText'] = CHeader.prototype.get_headerText;
	CHeader.prototype['get_pageNumber'] = CHeader.prototype.get_pageNumber;
	CHeader.prototype['get_X'] = CHeader.prototype.get_X;
	CHeader.prototype['get_Y'] = CHeader.prototype.get_Y;
	CHeader.prototype['get_Level'] = CHeader.prototype.get_Level;

	/**
	 * Класс для работы с настройками таблицы содержимого
	 * @constructor
	 */
	function CTableOfContentsPr()
	{
		this.Hyperlink    = true;
		this.OutlineStart = -1;
		this.OutlineEnd   = -1;
		this.Styles       = [];
		this.PageNumbers  = true;
		this.RightTab     = true;

		// Эти параметры задаются только из интерфейса
		this.TabLeader    = undefined;

		this.StylesType   = Asc.c_oAscTOCStylesType.Current;

		this.ComplexField = null;
	}
	CTableOfContentsPr.prototype.InitFromTOCInstruction = function(oComplexField)
	{
		if (!oComplexField)
			return;

		var oInstruction = oComplexField.GetInstruction();
		if (!oInstruction)
			return;

		this.Hyperlink    = oInstruction.IsHyperlinks();
		this.OutlineStart = oInstruction.GetHeadingRangeStart();
		this.OutlineEnd   = oInstruction.GetHeadingRangeEnd();
		this.Styles       = oInstruction.GetStylesArray();

		this.PageNumbers  = !oInstruction.IsSkipPageRefLvl();
		this.RightTab     = "" === oInstruction.GetSeparator();

		var oBeginChar = oComplexField.GetBeginChar();
		if (oBeginChar && oBeginChar.GetRun() && oBeginChar.GetRun().GetParagraph())
		{
			var oTabs = oBeginChar.GetRun().GetParagraph().GetParagraphTabs();

			if (oTabs.Tabs.length > 0)
			{
				this.TabLeader = oTabs.Tabs[oTabs.Tabs.length - 1].Leader;
			}
		}

		this.ComplexField = oComplexField;
	};
	CTableOfContentsPr.prototype.InitFromSdtTOC = function(oSdtTOC)
	{
		this.ComplexField = oSdtTOC;
	};
	CTableOfContentsPr.prototype.CheckStylesType = function(oStyles)
	{
		if (oStyles)
			this.StylesType = oStyles.GetTOCStylesType();
	};
	CTableOfContentsPr.prototype.get_Hyperlink = function()
	{
		return this.Hyperlink;
	};
	CTableOfContentsPr.prototype.put_Hyperlink = function(isHyperlink)
	{
		this.Hyperlink = isHyperlink;
	};
	CTableOfContentsPr.prototype.get_OutlineStart = function()
	{
		return this.OutlineStart;
	};
	CTableOfContentsPr.prototype.get_OutlineEnd = function()
	{
		return this.OutlineEnd;
	};
	CTableOfContentsPr.prototype.put_OutlineRange = function(nStart, nEnd)
	{
		this.OutlineStart = nStart;
		this.OutlineEnd   = nEnd;
	};
	CTableOfContentsPr.prototype.get_StylesCount = function()
	{
		return this.Styles.length;
	};
	CTableOfContentsPr.prototype.get_StyleName = function(nIndex)
	{
		if (nIndex < 0 || nIndex >= this.Styles.length)
			return "";

		return this.Styles[nIndex].Name;
	};
	CTableOfContentsPr.prototype.get_StyleLevel = function(nIndex)
	{
		if (nIndex < 0 || nIndex >= this.Styles.length)
			return -1;

		return this.Styles[nIndex].Lvl;
	};
	CTableOfContentsPr.prototype.get_Styles = function()
	{
		return this.Styles;
	};
	CTableOfContentsPr.prototype.clear_Styles = function()
	{
		this.Styles = [];
	};
	CTableOfContentsPr.prototype.add_Style = function(sName, nLvl)
	{
		this.Styles.push({Name : sName, Lvl : nLvl});
	};
	CTableOfContentsPr.prototype.put_ShowPageNumbers = function(isShow)
	{
		this.PageNumbers = isShow;
	};
	CTableOfContentsPr.prototype.get_ShowPageNumbers = function()
	{
		return this.PageNumbers;
	};
	CTableOfContentsPr.prototype.put_RightAlignTab = function(isRightTab)
	{
		this.RightTab = isRightTab;
	};
	CTableOfContentsPr.prototype.get_RightAlignTab = function()
	{
		return this.RightTab;
	};
	CTableOfContentsPr.prototype.put_TabLeader = function(nTabLeader)
	{
		this.TabLeader = nTabLeader;
	};
	CTableOfContentsPr.prototype.get_TabLeader = function()
	{
		return this.TabLeader;
	};
	CTableOfContentsPr.prototype.get_StylesType = function()
	{
		return this.StylesType;
	};
	CTableOfContentsPr.prototype.put_StylesType = function(nType)
	{
		this.StylesType = nType;
	};
	CTableOfContentsPr.prototype.get_InternalClass = function()
	{
		return this.ComplexField;
	};


	window['Asc']['CTableOfContentsPr'] = window['Asc'].CTableOfContentsPr = CTableOfContentsPr;
	CTableOfContentsPr.prototype['get_Hyperlink']       = CTableOfContentsPr.prototype.get_Hyperlink;
	CTableOfContentsPr.prototype['put_Hyperlink']       = CTableOfContentsPr.prototype.put_Hyperlink;
	CTableOfContentsPr.prototype['get_OutlineStart']    = CTableOfContentsPr.prototype.get_OutlineStart;
	CTableOfContentsPr.prototype['get_OutlineEnd']      = CTableOfContentsPr.prototype.get_OutlineEnd;
	CTableOfContentsPr.prototype['put_OutlineRange']    = CTableOfContentsPr.prototype.put_OutlineRange;
	CTableOfContentsPr.prototype['get_StylesCount']     = CTableOfContentsPr.prototype.get_StylesCount;
	CTableOfContentsPr.prototype['get_StyleName']       = CTableOfContentsPr.prototype.get_StyleName;
	CTableOfContentsPr.prototype['get_StyleLevel']      = CTableOfContentsPr.prototype.get_StyleLevel;
	CTableOfContentsPr.prototype['clear_Styles']        = CTableOfContentsPr.prototype.clear_Styles;
	CTableOfContentsPr.prototype['add_Style']           = CTableOfContentsPr.prototype.add_Style;
	CTableOfContentsPr.prototype['put_ShowPageNumbers'] = CTableOfContentsPr.prototype.put_ShowPageNumbers;
	CTableOfContentsPr.prototype['get_ShowPageNumbers'] = CTableOfContentsPr.prototype.get_ShowPageNumbers;
	CTableOfContentsPr.prototype['put_RightAlignTab']   = CTableOfContentsPr.prototype.put_RightAlignTab;
	CTableOfContentsPr.prototype['get_RightAlignTab']   = CTableOfContentsPr.prototype.get_RightAlignTab;
	CTableOfContentsPr.prototype['get_TabLeader']       = CTableOfContentsPr.prototype.get_TabLeader;
	CTableOfContentsPr.prototype['put_TabLeader']       = CTableOfContentsPr.prototype.put_TabLeader;
	CTableOfContentsPr.prototype['get_StylesType']      = CTableOfContentsPr.prototype.get_StylesType;
	CTableOfContentsPr.prototype['put_StylesType']      = CTableOfContentsPr.prototype.put_StylesType;
	CTableOfContentsPr.prototype['get_InternalClass']   = CTableOfContentsPr.prototype.get_InternalClass;


	/**
	 * Класс для работы с настройками стиля
	 * @constructor
	 */
	function CAscStyle()
	{
		this.Name = "";
		this.Type = Asc.c_oAscStyleType.Paragraph;

		this.qFormat    = undefined;
		this.uiPriority = undefined;

		this.StyleId  = "";
	}
	CAscStyle.prototype.get_Name = function()
	{
		return this.Name;
	};
	CAscStyle.prototype.put_Name = function(sName)
	{
		this.Name = sName;
	};
	CAscStyle.prototype.get_Type = function()
	{
		return this.Type;
	};
	CAscStyle.prototype.put_Type = function(nType)
	{
		this.Type = nType;
	};
	CAscStyle.prototype.get_QFormat = function()
	{
		return this.qFormat;
	};
	CAscStyle.prototype.put_QFormat = function(isQFormat)
	{
		this.qFormat = isQFormat;
	};
	CAscStyle.prototype.get_UIPriority = function()
	{
		return this.uiPriority;
	};
	CAscStyle.prototype.put_UIPriority = function(nPriority)
	{
		this.uiPriority = nPriority;
	};
	CAscStyle.prototype.get_StyleId = function()
	{
		return this.StyleId;
	};

	window['Asc']['CAscStyle'] = window['Asc'].CAscStyle = CAscStyle;
	CAscStyle.prototype['get_Name']       = CAscStyle.prototype.get_Name;
	CAscStyle.prototype['put_Name']       = CAscStyle.prototype.put_Name;
	CAscStyle.prototype['get_Type']       = CAscStyle.prototype.get_Type;
	CAscStyle.prototype['put_Type']       = CAscStyle.prototype.put_Type;
	CAscStyle.prototype['get_QFormat']    = CAscStyle.prototype.get_QFormat;
	CAscStyle.prototype['put_QFormat']    = CAscStyle.prototype.put_QFormat;
	CAscStyle.prototype['get_UIPriority'] = CAscStyle.prototype.get_UIPriority;
	CAscStyle.prototype['put_UIPriority'] = CAscStyle.prototype.put_UIPriority;
	CAscStyle.prototype['get_StyleId']    = CAscStyle.prototype.get_StyleId;


	/**
	 * Класс для работы с настройками нумерации
	 * @constructor
	 */
	function CAscNumbering()
	{
		this.NumId = "";
		this.Lvl   = new Array(9);
		for (var nLvl = 0; nLvl < 9; ++nLvl)
		{
			this.Lvl[nLvl] = new CAscNumberingLvl(nLvl);
		}
	}
	CAscNumbering.prototype.get_InternalId = function()
	{
		return this.NumId;
	};
	CAscNumbering.prototype.get_Lvl = function(nLvl)
	{
		if (nLvl < 0)
			return this.Lvl[0];
		else if (nLvl > 8)
			return this.Lvl[8];
		else if (!this.Lvl[nLvl])
			return this.Lvl[0];

		return this.Lvl[nLvl];
	};
	window['Asc']['CAscNumbering'] = window['Asc'].CAscNumbering = CAscNumbering;
	CAscNumbering.prototype['get_InternalId'] = CAscNumbering.prototype.get_InternalId;
	CAscNumbering.prototype['get_Lvl']        = CAscNumbering.prototype.get_Lvl;


	/**
	 * Класс для работы с текстом конкретного уровня нумерации
	 * @constructor
	 */
	function CAscNumberingLvlText(Type, Value)
	{
		this.Type  = undefined !== Type ? Type : Asc.c_oAscNumberingLvlTextType.Text;
		this.Value = undefined !== Value ? Value : "";
	}
	CAscNumberingLvlText.prototype.get_Type = function()
	{
		return this.Type;
	};
	CAscNumberingLvlText.prototype.put_Type = function(nType)
	{
		this.Type = nType;
	};
	CAscNumberingLvlText.prototype.get_Value = function()
	{
		return this.Value;
	};
	CAscNumberingLvlText.prototype.put_Value = function(vVal)
	{
		this.Value = vVal;
	};
	window['Asc']['CAscNumberingLvlText'] = window['Asc'].CAscNumberingLvlText = CAscNumberingLvlText;
	CAscNumberingLvlText.prototype['get_Type']  = CAscNumberingLvlText.prototype.get_Type;
	CAscNumberingLvlText.prototype['put_Type']  = CAscNumberingLvlText.prototype.put_Type;
	CAscNumberingLvlText.prototype['get_Value'] = CAscNumberingLvlText.prototype.get_Value;
	CAscNumberingLvlText.prototype['put_Value'] = CAscNumberingLvlText.prototype.put_Value;


	/**
	 * Класс для работы с настройками конкретного уровня нумерации
	 * @constructor
	 */
	function CAscNumberingLvl(nLvlNum)
	{
		this.LvlNum  = nLvlNum;
		this.Format  = Asc.c_oAscNumberingFormat.Bullet;
		this.Text    = [];
		this.TextPr  = new AscCommonWord.CTextPr();
		this.ParaPr  = new AscCommonWord.CParaPr();
		this.Start   = 1;
		this.Restart = -1;
		this.Suff    = Asc.c_oAscNumberingSuff.Tab;
		this.Align   = AscCommon.align_Left;
	}
	CAscNumberingLvl.prototype.get_LvlNum = function()
	{
		return this.LvlNum;
	};
	CAscNumberingLvl.prototype.get_Format = function()
	{
		return this.Format;
	};
	CAscNumberingLvl.prototype.put_Format = function(nFormat)
	{
		this.Format = nFormat;
	};
	CAscNumberingLvl.prototype.get_Text = function()
	{
		return this.Text;
	};
	CAscNumberingLvl.prototype.put_Text = function(arrText)
	{
		this.Text = arrText;
	};
	CAscNumberingLvl.prototype.get_TextPr = function()
	{
		return this.TextPr;
	};
	CAscNumberingLvl.prototype.get_ParaPr = function()
	{
		return this.ParaPr;
	};
	CAscNumberingLvl.prototype.get_Start = function()
	{
		return this.Start;
	};
	CAscNumberingLvl.prototype.put_Start = function(nStart)
	{
		this.Start = nStart;
	};
	CAscNumberingLvl.prototype.get_Restart = function()
	{
		return this.Restart;
	};
	CAscNumberingLvl.prototype.put_Restart = function(nRestart)
	{
		this.Restart = nRestart;
	};
	CAscNumberingLvl.prototype.get_Suff = function()
	{
		return this.Suff;
	};
	CAscNumberingLvl.prototype.put_Suff = function(nSuff)
	{
		this.Suff = nSuff;
	};
	CAscNumberingLvl.prototype.get_Align = function()
	{
		return this.Align;
	};
	CAscNumberingLvl.prototype.put_Align = function(nAlign)
	{
		this.Align = nAlign;
	};
	window['Asc']['CAscNumberingLvl'] = window['Asc'].CAscNumberingLvl = CAscNumberingLvl;
	CAscNumberingLvl.prototype['get_LvlNum']  = CAscNumberingLvl.prototype.get_LvlNum;
	CAscNumberingLvl.prototype['get_Format']  = CAscNumberingLvl.prototype.get_Format;
	CAscNumberingLvl.prototype['put_Format']  = CAscNumberingLvl.prototype.put_Format;
	CAscNumberingLvl.prototype['get_Text']    = CAscNumberingLvl.prototype.get_Text;
	CAscNumberingLvl.prototype['put_Text']    = CAscNumberingLvl.prototype.put_Text;
	CAscNumberingLvl.prototype['get_TextPr']  = CAscNumberingLvl.prototype.get_TextPr;
	CAscNumberingLvl.prototype['get_ParaPr']  = CAscNumberingLvl.prototype.get_ParaPr;
	CAscNumberingLvl.prototype['get_Start']   = CAscNumberingLvl.prototype.get_Start;
	CAscNumberingLvl.prototype['put_Start']   = CAscNumberingLvl.prototype.put_Start;
	CAscNumberingLvl.prototype['get_Restart'] = CAscNumberingLvl.prototype.get_Restart;
	CAscNumberingLvl.prototype['put_Restart'] = CAscNumberingLvl.prototype.put_Restart;
	CAscNumberingLvl.prototype['get_Suff']    = CAscNumberingLvl.prototype.get_Suff;
	CAscNumberingLvl.prototype['put_Suff']    = CAscNumberingLvl.prototype.put_Suff;
	CAscNumberingLvl.prototype['get_Align']   = CAscNumberingLvl.prototype.get_Align;
	CAscNumberingLvl.prototype['put_Align']   = CAscNumberingLvl.prototype.put_Align;
})(window, undefined);
/*
 * (c) Copyright Ascensio System SIA 2010-2018
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";

var editor;
(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
  function(window, undefined) {
  var asc = window["Asc"];
  var prot;

  var c_oAscAdvancedOptionsAction = AscCommon.c_oAscAdvancedOptionsAction;
  var DownloadType = AscCommon.DownloadType;
  var c_oAscLockTypes = AscCommon.c_oAscLockTypes;
  var CColor = AscCommon.CColor;
  var g_oDocumentUrls = AscCommon.g_oDocumentUrls;
  var sendCommand = AscCommon.sendCommand;
  var mapAscServerErrorToAscError = AscCommon.mapAscServerErrorToAscError;
  var parserHelp = AscCommon.parserHelp;
  var g_oIdCounter = AscCommon.g_oIdCounter;
  var g_oTableId = AscCommon.g_oTableId;

  var c_oAscLockTypeElem = AscCommonExcel.c_oAscLockTypeElem;

  var c_oAscError = asc.c_oAscError;
  var c_oAscFileType = asc.c_oAscFileType;
  var c_oAscAsyncAction = asc.c_oAscAsyncAction;
  var c_oAscAdvancedOptionsID = asc.c_oAscAdvancedOptionsID;
  var c_oAscAsyncActionType = asc.c_oAscAsyncActionType;

  var History = null;


  /**
   *
   * @param config
   * @param eventsHandlers
   * @constructor
   * @returns {spreadsheet_api}
   * @extends {AscCommon.baseEditorsApi}
   */
  function spreadsheet_api(config) {
    AscCommon.baseEditorsApi.call(this, config, AscCommon.c_oEditorId.Spreadsheet);

    /************ private!!! **************/
    this.topLineEditorName = config['id-input'] || '';
    this.topLineEditorElement = null;

    this.controller = null;

    this.handlers = new AscCommonExcel.asc_CHandlersList();
    // Вид печати
    this.adjustPrint = null;

    this.fontRenderingMode = Asc.c_oAscFontRenderingModeType.hintingAndSubpixeling;
    this.wb = null;
    this.wbModel = null;
    this.tmpLocale = null;
    this.tmpLocalization = null;

    this.documentFormatSave = c_oAscFileType.XLSX;

    // объекты, нужные для отправки в тулбар (шрифты, стили)
    this._gui_control_colors = null;
    this.GuiControlColorsMap = null;
    this.IsSendStandartColors = false;

    this.asyncMethodCallback = undefined;

    // Переменная отвечает, загрузились ли фонты
    this.FontLoadWaitComplete = false;
    //текущий обьект куда записываются информация для update, когда принимаются изменения в native редакторе
    this.oRedoObjectParamNative = null;

    this.collaborativeEditing = null;

    // AutoSave
    this.autoSaveGapRealTime = 30;	  // Интервал быстрого автосохранения (когда выставлен флаг realtime) - 30 мс.

    // Shapes
    this.isStartAddShape = false;
    this.shapeElementId = null;
    this.textArtElementId = null;
    this.isImageChangeUrl = false;
    this.isShapeImageChangeUrl = false;
    this.isTextArtChangeUrl = false;
    this.textureType = null;


	  // Styles sizes
      this.styleThumbnailWidth = 112;
	  this.styleThumbnailHeight = 38;

    this.formulasList = null;	// Список всех формул

    if (window.editor == undefined) {
       window.editor = this;
    }

    this._init();
    return this;
  }
  spreadsheet_api.prototype = Object.create(AscCommon.baseEditorsApi.prototype);
  spreadsheet_api.prototype.constructor = spreadsheet_api;
  spreadsheet_api.prototype.sendEvent = function() {
    this.handlers.trigger.apply(this.handlers, arguments);
  };

  spreadsheet_api.prototype._init = function() {
    AscCommon.baseEditorsApi.prototype._init.call(this);
    this.topLineEditorElement = document.getElementById(this.topLineEditorName);
    // ToDo нужно ли это
    asc['editor'] = ( asc['editor'] || this );
    AscCommon.AscBrowser.checkZoom();
  };

  spreadsheet_api.prototype.asc_CheckGuiControlColors = function() {
    // потом реализовать проверку на то, что нужно ли посылать

    var arr_colors = new Array(10);
    var _count = arr_colors.length;
    for (var i = 0; i < _count; ++i) {
      var color = AscCommonExcel.g_oColorManager.getThemeColor(i);
      arr_colors[i] = new CColor(color.getR(), color.getG(), color.getB());
    }

    // теперь проверим
    var bIsSend = false;
    if (this.GuiControlColorsMap != null) {
      for (var i = 0; i < _count; ++i) {
        var _color1 = this.GuiControlColorsMap[i];
        var _color2 = arr_colors[i];

        if ((_color1.r !== _color2.r) || (_color1.g !== _color2.g) || (_color1.b !== _color2.b)) {
          bIsSend = true;
          break;
        }
      }
    } else {
      this.GuiControlColorsMap = new Array(_count);
      bIsSend = true;
    }

    if (bIsSend) {
      for (var i = 0; i < _count; ++i) {
        this.GuiControlColorsMap[i] = arr_colors[i];
      }

      this.asc_SendControlColors();
    }
  };

  spreadsheet_api.prototype.asc_SendControlColors = function() {
    var standart_colors = null;
    if (!this.IsSendStandartColors) {
      var standartColors = AscCommon.g_oStandartColors;
      var _c_s = standartColors.length;
      standart_colors = new Array(_c_s);

      for (var i = 0; i < _c_s; ++i) {
        standart_colors[i] = new CColor(standartColors[i].R, standartColors[i].G, standartColors[i].B);
      }

      this.IsSendStandartColors = true;
    }

    var _count = this.GuiControlColorsMap.length;

    var _ret_array = new Array(_count * 6);
    var _cur_index = 0;

    for (var i = 0; i < _count; ++i) {
      var basecolor = AscCommonExcel.g_oColorManager.getThemeColor(i);
      var aTints = AscCommonExcel.g_oThemeColorsDefaultModsSpreadsheet[AscCommon.GetDefaultColorModsIndex(basecolor.getR(), basecolor.getG(), basecolor.getB())];
      for (var j = 0, length = aTints.length; j < length; ++j) {
        var tint = aTints[j];
        var color = AscCommonExcel.g_oColorManager.getThemeColor(i, tint);
        _ret_array[_cur_index] = new CColor(color.getR(), color.getG(), color.getB());
        _cur_index++;
      }
    }

    this.asc_SendThemeColors(_ret_array, standart_colors);
  };

  spreadsheet_api.prototype.asc_getCurrencySymbols = function () {
		var result = {};
		for (var key in AscCommon.g_aCultureInfos) {
			result[key] = AscCommon.g_aCultureInfos[key].CurrencySymbol;
		}
		return result;
	};
	spreadsheet_api.prototype.asc_getLocaleExample = function(format, value, culture) {
		var cultureInfo = AscCommon.g_aCultureInfos[culture] || AscCommon.g_oDefaultCultureInfo;
		var numFormat = AscCommon.oNumFormatCache.get(format);
		var res;
		if (null == value) {
			var ws = this.wbModel.getActiveWs();
			var activeCell = ws.selectionRange.activeCell;
			ws._getCellNoEmpty(activeCell.row, activeCell.col, function(cell) {
              if (cell) {
                res = cell.getValueForExample(numFormat, cultureInfo);
              } else {
                res = '';
              }
            });
		} else {
			res = numFormat.formatToChart(value, undefined, cultureInfo);
		}
		return res;
	};
	spreadsheet_api.prototype.asc_getFormatCells = function(info) {
		return AscCommon.getFormatCells(info);
	};
  spreadsheet_api.prototype.asc_getLocaleCurrency = function(val) {
    var cultureInfo = AscCommon.g_aCultureInfos[val];
    if (!cultureInfo) {
      cultureInfo = AscCommon.g_aCultureInfos[1033];
    }
    return AscCommonExcel.getCurrencyFormat(cultureInfo, 2, true, true);
  };


  spreadsheet_api.prototype.asc_getCurrentListType = function(){
      var ws = this.wb.getWorksheet();
      var oParaPr;
      if (ws && ws.objectRender && ws.objectRender.controller) {
          oParaPr = ws.objectRender.controller.getParagraphParaPr();
      }
      return new AscCommon.asc_CListType(AscFormat.fGetListTypeFromBullet(oParaPr && oParaPr.Bullet));
  };

    spreadsheet_api.prototype.asc_setLocale = function(val) {
    if (!this.isLoadFullApi) {
      this.tmpLocale = val;
      return;
    }
    if (null === val) {
      return;
    }
    if (AscCommon.setCurrentCultureInfo(val)) {
      parserHelp.setDigitSeparator(AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator);
      if (this.wbModel) {
        AscCommon.oGeneralEditFormatCache.cleanCache();
        AscCommon.oNumFormatCache.cleanCache();
        this.wbModel.rebuildColors();
        if (this.isDocumentLoadComplete) {
          AscCommon.checkCultureInfoFontPicker();
          this._loadFonts([], function() {
            this._onUpdateAfterApplyChanges();
          });
        }
      }
    }
  };
	spreadsheet_api.prototype.asc_getLocale = function() {
		return AscCommon.g_oDefaultCultureInfo.LCID;
	};

  spreadsheet_api.prototype._openDocument = function(data) {
    this.wbModel = new AscCommonExcel.Workbook(this.handlers, this);
    this.initGlobalObjects(this.wbModel);
    AscFonts.IsCheckSymbols = true;
    var oBinaryFileReader = new AscCommonExcel.BinaryFileReader();
    oBinaryFileReader.Read(data, this.wbModel);
    AscFonts.IsCheckSymbols = false;
  };

  spreadsheet_api.prototype.initGlobalObjects = function(wbModel) {
    // History & global counters
    History.init(wbModel);

    AscCommonExcel.g_oUndoRedoCell = new AscCommonExcel.UndoRedoCell(wbModel);
    AscCommonExcel.g_oUndoRedoWorksheet = new AscCommonExcel.UndoRedoWoorksheet(wbModel);
    AscCommonExcel.g_oUndoRedoWorkbook = new AscCommonExcel.UndoRedoWorkbook(wbModel);
    AscCommonExcel.g_oUndoRedoCol = new AscCommonExcel.UndoRedoRowCol(wbModel, false);
    AscCommonExcel.g_oUndoRedoRow = new AscCommonExcel.UndoRedoRowCol(wbModel, true);
    AscCommonExcel.g_oUndoRedoComment = new AscCommonExcel.UndoRedoComment(wbModel);
    AscCommonExcel.g_oUndoRedoAutoFilters = new AscCommonExcel.UndoRedoAutoFilters(wbModel);
    AscCommonExcel.g_oUndoRedoSparklines = new AscCommonExcel.UndoRedoSparklines(wbModel);
    AscCommonExcel.g_oUndoRedoPivotTables = new AscCommonExcel.UndoRedoPivotTables(wbModel);
    AscCommonExcel.g_DefNameWorksheet = new AscCommonExcel.Worksheet(wbModel, -1);
    AscCommonExcel.g_oUndoRedoSharedFormula = new AscCommonExcel.UndoRedoSharedFormula(wbModel);
    AscCommonExcel.g_oUndoRedoLayout = new AscCommonExcel.UndoRedoRedoLayout(wbModel);
  };

  spreadsheet_api.prototype.asc_DownloadAs = function(typeFile, bIsDownloadEvent, adjustPrint) {//передаем число соответствующее своему формату. например  c_oAscFileType.XLSX
    if (!this.canSave || this.isChartEditor || c_oAscAdvancedOptionsAction.None !== this.advancedOptionsAction) {
      return;
    }

    if (c_oAscFileType.PDF === typeFile || c_oAscFileType.PDFA === typeFile) {
      this.adjustPrint = adjustPrint ? adjustPrint : new Asc.asc_CAdjustPrint();
    }
    this._asc_downloadAs(typeFile, c_oAscAsyncAction.DownloadAs, {downloadType: bIsDownloadEvent ? DownloadType.Download: DownloadType.None});
  };
	spreadsheet_api.prototype._saveCheck = function() {
		return !this.isChartEditor && c_oAscAdvancedOptionsAction.None === this.advancedOptionsAction &&
			!this.isLongAction() && !this.asc_getIsTrackShape() && !this.isOpenedChartFrame &&
			History.IsEndTransaction();
	};
	spreadsheet_api.prototype._haveOtherChanges = function () {
	  return this.collaborativeEditing.haveOtherChanges();
    };
	spreadsheet_api.prototype._prepareSave = function (isIdle) {
		var tmpHandlers;
		if (isIdle) {
			tmpHandlers = this.wbModel.handlers.handlers['asc_onError'];
			this.wbModel.handlers.handlers['asc_onError'] = null;
		}

      /* Нужно закрыть редактор (до выставления флага canSave, т.к. мы должны успеть отправить
       asc_onDocumentModifiedChanged для подписки на сборку) Баг http://bugzilla.onlyoffice.com/show_bug.cgi?id=28331 */
		if (!this.asc_closeCellEditor()) {
			if (isIdle) {
				this.asc_closeCellEditor(true);
			} else {
				return false;
			}
		}

		if (isIdle) {
			this.wbModel.handlers.handlers['asc_onError'] = tmpHandlers;
		}
		return true;
    };

  spreadsheet_api.prototype.asc_Print = function(adjustPrint, bIsDownloadEvent) {
    if (window["AscDesktopEditor"]) {
      window.AscDesktopEditor_PrintData = adjustPrint;
      window["AscDesktopEditor"]["Print"]();
      return;
    }

    this.adjustPrint = adjustPrint ? adjustPrint : new Asc.asc_CAdjustPrint();
    this._asc_downloadAs(c_oAscFileType.PDF, c_oAscAsyncAction.Print, {downloadType: bIsDownloadEvent ? DownloadType.Print: DownloadType.None});
  };

  spreadsheet_api.prototype.asc_Copy = function() {
    if (window["AscDesktopEditor"])
    {
      window["asc_desktop_copypaste"](this, "Copy");
      return true;
    }
    return AscCommon.g_clipboardBase.Button_Copy();
  };

  spreadsheet_api.prototype.asc_Paste = function() {
    if (window["AscDesktopEditor"])
    {
      window["asc_desktop_copypaste"](this, "Paste");
      return true;
    }
    if (!AscCommon.g_clipboardBase.IsWorking()) {
      return AscCommon.g_clipboardBase.Button_Paste();
    }
    return false;
  };
  
  spreadsheet_api.prototype.asc_SpecialPaste = function(props) {
    return AscCommon.g_specialPasteHelper.Special_Paste(props);
  };
  
  spreadsheet_api.prototype.asc_SpecialPasteData = function(props) {
	if (this.canEdit()) {
      this.wb.specialPasteData(props);
    }
  };

  spreadsheet_api.prototype.asc_ShowSpecialPasteButton = function(props) {
      if (this.canEdit()) {
          this.wb.showSpecialPasteButton(props);
      }
  };

  spreadsheet_api.prototype.asc_UpdateSpecialPasteButton = function(props) {
      if (this.canEdit()) {
          this.wb.updateSpecialPasteButton(props);
      }
  };

  spreadsheet_api.prototype.asc_HideSpecialPasteButton = function() {
      if (this.canEdit()) {
          this.wb.hideSpecialPasteButton();
      }
 };

  spreadsheet_api.prototype.asc_Cut = function() {
    if (window["AscDesktopEditor"])
    {
      window["asc_desktop_copypaste"](this, "Cut");
      return true;
    }
    return AscCommon.g_clipboardBase.Button_Cut();
  };

  spreadsheet_api.prototype.asc_PasteData = function (_format, data1, data2, text_data) {
    if (this.canEdit()) {
      this.wb.pasteData(_format, data1, data2, text_data, arguments[5]);
    }
  };

  spreadsheet_api.prototype.asc_CheckCopy = function (_clipboard /* CClipboardData */, _formats) {
    return this.wb.checkCopyToClipboard(_clipboard, _formats);
  };

  spreadsheet_api.prototype.asc_SelectionCut = function () {
    if (this.canEdit()) {
      this.wb.selectionCut();
    }
  };

  spreadsheet_api.prototype.asc_bIsEmptyClipboard = function() {
    var result = this.wb.bIsEmptyClipboard();
    this.wb.restoreFocus();
    return result;
  };

  spreadsheet_api.prototype.asc_Undo = function() {
    this.wb.undo();
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_Redo = function() {
    this.wb.redo();
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_Resize = function () {
    AscCommon.AscBrowser.checkZoom();
    if (this.wb) {
      this.wb.resize();

      if (AscCommon.g_inputContext) {
        AscCommon.g_inputContext.onResize("ws-canvas-outer");
      }
    }
  };

  spreadsheet_api.prototype.asc_addAutoFilter = function(styleName, addFormatTableOptionsObj) {
    var ws = this.wb.getWorksheet();
    return ws.addAutoFilter(styleName, addFormatTableOptionsObj);
  };

  spreadsheet_api.prototype.asc_changeAutoFilter = function(tableName, optionType, val) {
    var ws = this.wb.getWorksheet();
    return ws.changeAutoFilter(tableName, optionType, val);
  };

  spreadsheet_api.prototype.asc_applyAutoFilter = function(autoFilterObject) {
    var ws = this.wb.getWorksheet();
    ws.applyAutoFilter(autoFilterObject);
  };
  
  spreadsheet_api.prototype.asc_applyAutoFilterByType = function(autoFilterObject) {
    var ws = this.wb.getWorksheet();
    ws.applyAutoFilterByType(autoFilterObject);
  };
  
  spreadsheet_api.prototype.asc_reapplyAutoFilter = function(displayName) {
    var ws = this.wb.getWorksheet();
    ws.reapplyAutoFilter(displayName);
  };

  spreadsheet_api.prototype.asc_sortColFilter = function(type, cellId, displayName, color, bIsExpandRange) {
    var ws = this.wb.getWorksheet();
    ws.sortRange(type, cellId, displayName, color, bIsExpandRange);
  };

  spreadsheet_api.prototype.asc_getAddFormatTableOptions = function(range) {
    var ws = this.wb.getWorksheet();
    return ws.getAddFormatTableOptions(range);
  };

  spreadsheet_api.prototype.asc_clearFilter = function() {
    var ws = this.wb.getWorksheet();
    return ws.clearFilter();
  };
  
  spreadsheet_api.prototype.asc_clearFilterColumn = function(cellId, displayName) {
    var ws = this.wb.getWorksheet();
    return ws.clearFilterColumn(cellId, displayName);
  };
  
  spreadsheet_api.prototype.asc_changeSelectionFormatTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeSelectionFormatTable(tableName, optionType);
  };
  
  spreadsheet_api.prototype.asc_changeFormatTableInfo = function(tableName, optionType, val) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeFormatTableInfo(tableName, optionType, val);
  };

  spreadsheet_api.prototype.asc_applyAutoCorrectOptions = function(val) {
      this.wb.applyAutoCorrectOptions(val);
  };

  spreadsheet_api.prototype.asc_insertCellsInTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
    return ws.af_insertCellsInTable(tableName, optionType);
  };
  
  spreadsheet_api.prototype.asc_deleteCellsInTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
    return ws.af_deleteCellsInTable(tableName, optionType);
  };
  
  spreadsheet_api.prototype.asc_changeDisplayNameTable = function(tableName, newName) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeDisplayNameTable(tableName, newName);
  };
  
  spreadsheet_api.prototype.asc_changeTableRange = function(tableName, range) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeTableRange(tableName, range);
  };

  spreadsheet_api.prototype.asc_convertTableToRange = function(tableName) {
    var ws = this.wb.getWorksheet();
    return ws.af_convertTableToRange(tableName);
  };

	spreadsheet_api.prototype.asc_getTablePictures = function (props, pivot) {
		return this.wb.af_getTablePictures(props, pivot);
	};

  spreadsheet_api.prototype.asc_setViewMode = function (isViewMode) {
    this.isViewMode = !!isViewMode;
    if (!this.isLoadFullApi) {
      return;
    }
    if (this.collaborativeEditing) {
      this.collaborativeEditing.setViewerMode(isViewMode);
    }
  };

	  spreadsheet_api.prototype.asc_setFilteringMode = function (mode) {
		  window['AscCommonExcel'].filteringMode = !!mode;
	  };

  /*
   idOption идентификатор дополнительного параметра, пока c_oAscAdvancedOptionsID.CSV.
   option - какие свойства применить, пока массив. для CSV объект asc_CCSVAdvancedOptions(codepage, delimiter)
   exp:	asc_setAdvancedOptions(c_oAscAdvancedOptionsID.CSV, new Asc.asc_CCSVAdvancedOptions(1200, c_oAscCsvDelimiter.Comma) );
   */
  spreadsheet_api.prototype.asc_setAdvancedOptions = function(idOption, option) {
    var v;
    if (AscCommon.EncryptionWorker.asc_setAdvancedOptions(this, idOption, option))
      return;

    switch (idOption) {
      case c_oAscAdvancedOptionsID.CSV:
        // Проверяем тип состояния в данный момент
        if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Open) {
          v = {
            "id": this.documentId,
            "userid": this.documentUserId,
            "format": this.documentFormat,
            "c": "reopen",
            "url": this.documentUrl,
            "title": this.documentTitle,
            "delimiter": option.asc_getDelimiter(),
            "delimiterChar": option.asc_getDelimiterChar(),
            "codepage": option.asc_getCodePage(),
            "nobase64": true
          };

          sendCommand(this, null, v);
        } else {
          var options = {CSVOptions: option, downloadType: this.downloadType};
          this.downloadType = DownloadType.None;
          this._asc_downloadAs(c_oAscFileType.CSV, c_oAscAsyncAction.DownloadAs, options);
        }
        break;
      case c_oAscAdvancedOptionsID.DRM:
        // Проверяем тип состояния в данный момент
        if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Open) {
          v = {
            "id": this.documentId,
            "userid": this.documentUserId,
            "format": this.documentFormat,
            "c": "reopen",
            "url": this.documentUrl,
            "title": this.documentTitle,
            "password": option.asc_getPassword(),
            "nobase64": true
          };

          sendCommand(this, null, v);
        }
        break;
    }
  };
  // Опции страницы (для печати)
  spreadsheet_api.prototype.asc_setPageOptions = function(options, index) {
    var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
    this.wb.getWorksheet(sheetIndex).setPageOptions(options);
  };

  spreadsheet_api.prototype.asc_savePagePrintOptions = function(arrPagesPrint) {
      this.wb.savePagePrintOptions(arrPagesPrint);
  };

  spreadsheet_api.prototype.asc_getPageOptions = function(index) {
    var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
    return this.wbModel.getWorksheet(sheetIndex).PagePrintOptions;
  };

  spreadsheet_api.prototype.asc_setPageOption = function (func, val, index) {
      var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
      var ws = this.wb.getWorksheet(sheetIndex);
      ws.setPageOption(func, val);
  };

  spreadsheet_api.prototype.asc_changeDocSize = function (width, height, index) {
    var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
    var ws = this.wb.getWorksheet(sheetIndex);
    ws.changeDocSize(width, height);
  };

  spreadsheet_api.prototype.asc_changePageMargins = function (left, right, top, bottom, index) {
      var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
      var ws = this.wb.getWorksheet(sheetIndex);
      ws.changePageMargins(left, right, top, bottom);
  };

  spreadsheet_api.prototype.asc_changePageOrient = function (isPortrait, index) {
      var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
      var ws = this.wb.getWorksheet(sheetIndex);
      if (isPortrait) {
          ws.changePageOrient(Asc.c_oAscPageOrientation.PagePortrait);
      } else {
          ws.changePageOrient(Asc.c_oAscPageOrientation.PageLandscape);
      }
  };

  spreadsheet_api.prototype._onNeedParams = function(data, opt_isPassword) {
    var t = this;
    // Проверяем, возможно нам пришли опции для CSV
    if (this.documentOpenOptions && !opt_isPassword) {
      var codePageCsv = AscCommon.c_oAscEncodingsMap[this.documentOpenOptions["codePage"]] || AscCommon.c_oAscCodePageUtf8, delimiterCsv = this.documentOpenOptions["delimiter"],
		  delimiterCharCsv = this.documentOpenOptions["delimiterChar"];
      if (null != codePageCsv && (null != delimiterCsv || null != delimiterCharCsv)) {
        this.asc_setAdvancedOptions(c_oAscAdvancedOptionsID.CSV, new asc.asc_CCSVAdvancedOptions(codePageCsv, delimiterCsv));
        return;
      }
    }
	if (opt_isPassword) {
		if (t.handlers.hasTrigger("asc_onAdvancedOptions")) {
			t.handlers.trigger("asc_onAdvancedOptions", new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.DRM), this.advancedOptionsAction);
		} else {
			t.handlers.trigger("asc_onError", c_oAscError.ID.ConvertationPassword, c_oAscError.Level.Critical);
		}
	} else {
		if (t.handlers.hasTrigger("asc_onAdvancedOptions")) {
			// ToDo разделитель пока только "," http://bugzilla.onlyoffice.com/show_bug.cgi?id=31009
			var cp = {
				'codepage': AscCommon.c_oAscCodePageUtf8, "delimiter": AscCommon.c_oAscCsvDelimiter.Comma,
				'encodings': AscCommon.getEncodingParams()
			};
			var options;
			if (data && typeof Blob !== 'undefined' && typeof FileReader !== 'undefined') {
				AscCommon.getJSZipUtils().getBinaryContent(data, function(err, data) {
					if (err) {
						t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.Critical);
					} else {
						var dataUint = new Uint8Array(data);
						var bom = AscCommon.getEncodingByBOM(dataUint);
						if (AscCommon.c_oAscCodePageNone !== bom.encoding) {
							cp['codepage'] = bom.encoding;
							data = dataUint.subarray(bom.size);
						}
						cp['data'] = data;
						options = new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.CSV, cp);
						t.handlers.trigger("asc_onAdvancedOptions", options, t.advancedOptionsAction);
					}
				});
			} else {
				options = new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.CSV, cp);
				t.handlers.trigger("asc_onAdvancedOptions", options, t.advancedOptionsAction);
			}
		} else {
			this.asc_setAdvancedOptions(c_oAscAdvancedOptionsID.CSV, new asc.asc_CCSVAdvancedOptions(AscCommon.c_oAscCodePageUtf8, AscCommon.c_oAscCsvDelimiter.Comma));
		}
    }
  };
  spreadsheet_api.prototype._onOpenCommand = function(data) {
    var t = this;
    AscCommon.openFileCommand(data, this.documentUrlChanges, AscCommon.c_oSerFormat.Signature, function(error, result) {
      if (error || !result.bSerFormat) {
        var err = error ? c_oAscError.ID.Unknown : c_oAscError.ID.ConvertationOpenError;
        var oError = {returnCode: c_oAscError.Level.Critical, val: err};
        t.handlers.trigger("asc_onError", oError.val, oError.returnCode);
        return;
      }

      t.onEndLoadFile(result.data);
    });
  };

  spreadsheet_api.prototype._OfflineAppDocumentEndLoad = function() {
    this.onEndLoadFile(AscCommonExcel.getEmptyWorkbook());
  };

  spreadsheet_api.prototype._asc_save2 = function () {
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
    var dataContainer = {data: null, part: null, index: 0, count: 0};
    dataContainer.data = oBinaryFileWriter.Write();
    var filetype = 0x1002;
    var oAdditionalData = {};
    oAdditionalData["c"] = "sfct";
    oAdditionalData["id"] = this.documentId;
    oAdditionalData["userid"] = this.documentUserId;
    oAdditionalData["jwt"] = this.CoAuthoringApi.get_jwt();
    oAdditionalData["outputformat"] = filetype;
    oAdditionalData["title"] =
        AscCommon.changeFileExtention(this.documentTitle, AscCommon.getExtentionByFormat(filetype));
    oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.CompleteAll;
    oAdditionalData["nobase64"] = true;
    var t = this;
    t.fCurCallback = function (incomeObject) {
      if (null != input && "save" == input["type"]) {
        if ('ok' == input["status"]) {
          var url = input["data"];
          if (url) {
            t.processSavedFile(url, false);
          } else {
            t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
          }
        } else {
          t.handlers.trigger("asc_onError",
              mapAscServerErrorToAscError(parseInt(input["data"]), AscCommon.c_oAscAdvancedOptionsAction.Save),
              c_oAscError.Level.NoCritical);
        }
      } else {
        t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
      }
    };
    AscCommon.saveWithParts(function (fCallback1, oAdditionalData1, dataContainer1) {
      sendCommand(t, fCallback1, oAdditionalData1, dataContainer1);
    }, t.fCurCallback, null, oAdditionalData, dataContainer);
  };

  spreadsheet_api.prototype._asc_downloadAs = function(sFormat, actionType, options) { //fCallback({returnCode:"", ...})
    var isCloudCrypto = (window["AscDesktopEditor"] && (0 < window["AscDesktopEditor"]["CryptoMode"])) ? true : false;
    if (isCloudCrypto)
      window.isCloudCryptoDownloadAs = true;

    var t = this;
    if (!options) {
      options = {};
    }
    if (actionType) {
      this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, actionType);
    }
    var isNoBase64 = (typeof ArrayBuffer !== 'undefined') && !isCloudCrypto;
    //sFormat: xlsx, xls, ods, csv, html
    var dataContainer = {data: null, part: null, index: 0, count: 0};
    var command = "save";
    var oAdditionalData = {};
    oAdditionalData["c"] = command;
    oAdditionalData["id"] = this.documentId;
    oAdditionalData["userid"] = this.documentUserId;
    oAdditionalData["jwt"] = this.CoAuthoringApi.get_jwt();
    oAdditionalData["outputformat"] = sFormat;
    oAdditionalData["title"] = AscCommon.changeFileExtention(this.documentTitle, AscCommon.getExtentionByFormat(sFormat), Asc.c_nMaxDownloadTitleLen);
    oAdditionalData["nobase64"] = isNoBase64;
    if (DownloadType.Print === options.downloadType) {
      oAdditionalData["inline"] = 1;
    }
    if (c_oAscFileType.PDF === sFormat || c_oAscFileType.PDFA === sFormat) {
      var printPagesData = this.wb.calcPagesPrint(this.adjustPrint);
      var pdfPrinterMemory = this.wb.printSheets(printPagesData).DocumentRenderer.Memory;
      dataContainer.data = isNoBase64 ? pdfPrinterMemory.GetData() : pdfPrinterMemory.GetBase64Memory();
    } else if (c_oAscFileType.CSV === sFormat && !options.CSVOptions) {
      // Мы открывали команду, надо ее закрыть.
      if (actionType) {
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
      }
      var cp = {'delimiter': AscCommon.c_oAscCsvDelimiter.Comma, 'codepage': AscCommon.c_oAscCodePageUtf8, 'encodings': AscCommon.getEncodingParams()};
      this.downloadType = options.downloadType;
      this.handlers.trigger("asc_onAdvancedOptions", new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.CSV, cp), c_oAscAdvancedOptionsAction.Save);
      return;
    } else {
      var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
      if (c_oAscFileType.CSV === sFormat) {
        if (options.CSVOptions instanceof asc.asc_CCSVAdvancedOptions) {
          oAdditionalData["codepage"] = options.CSVOptions.asc_getCodePage();
          oAdditionalData["delimiter"] = options.CSVOptions.asc_getDelimiter();
          oAdditionalData["delimiterChar"] = options.CSVOptions.asc_getDelimiterChar();
        }
      }
      dataContainer.data = oBinaryFileWriter.Write(isNoBase64);
    }
    // Меняем тип состояния (на сохранение)
    this.advancedOptionsAction = c_oAscAdvancedOptionsAction.Save;

    if (isCloudCrypto)
    {
      var sParamXml = ("<m_nCsvTxtEncoding>" + oAdditionalData["codepage"] + "</m_nCsvTxtEncoding>");
      sParamXml += ("<m_nCsvDelimiter>" + oAdditionalData["delimiter"] + "</m_nCsvDelimiter>");
      window["AscDesktopEditor"]["CryptoDownloadAs"](dataContainer.data, sFormat, sParamXml);
      return;
    }

    var fCallback = function(input) {
      var error = c_oAscError.ID.Unknown;
      if (null != input && command == input["type"]) {
        if ('ok' == input["status"]) {
          var url = input["data"];
          if (url) {
            error = c_oAscError.ID.No;
            t.processSavedFile(url, options.downloadType);
          }
        } else {
          error = mapAscServerErrorToAscError(parseInt(input["data"]), AscCommon.c_oAscAdvancedOptionsAction.Save);
        }
      }
      if (c_oAscError.ID.No != error) {
        t.handlers.trigger("asc_onError", error, c_oAscError.Level.NoCritical);
      }
      // Меняем тип состояния (на никакое)
      t.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;
      if (actionType) {
        t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
      }
    };
    t.fCurCallback = fCallback;
    AscCommon.saveWithParts(function(fCallback1, oAdditionalData1, dataContainer1) {
      sendCommand(t, fCallback1, oAdditionalData1, dataContainer1);
    }, fCallback, null, oAdditionalData, dataContainer);
  };

  spreadsheet_api.prototype.asc_isDocumentModified = function() {
    if (!this.canSave || this.asc_getCellEditMode()) {
      // Пока идет сохранение или редактирование ячейки, мы не закрываем документ
      return true;
    } else if (History && History.Have_Changes) {
      return History.Have_Changes();
    }
    return false;
  };

  // Actions and callbacks interface

  /*
   * asc_onStartAction			(type, id)
   * asc_onEndAction				(type, id)
   * asc_onInitEditorFonts		(gui_fonts)
   * asc_onInitEditorStyles		(gui_styles)
   * asc_onOpenDocumentProgress	(AscCommon.COpenProgress)
   * asc_onAdvancedOptions		(asc_CAdvancedOptions, ascAdvancedOptionsAction)	- эвент на получение дополнительных опций (открытие/сохранение CSV)
   * asc_onError					(c_oAscError.ID, c_oAscError.Level)					- эвент об ошибке
   * asc_onEditCell				(Asc.c_oAscCellEditorState)								- эвент на редактирование ячейки с состоянием (переходами из формулы и обратно)
   * asc_onEditorSelectionChanged	(asc_CFont)											- эвент на смену информации о выделении в редакторе ячейки
   * asc_onSelectionChanged		(asc_CCellInfo)										- эвент на смену информации о выделении
   * asc_onSelectionNameChanged	(sName)												- эвент на смену имени выделения (Id-ячейки, число выделенных столбцов/строк, имя диаграммы и др.)
   * asc_onSelection
   *
   * Changed	(asc_CSelectionMathInfo)							- эвент на смену математической информации о выделении
   * asc_onZoomChanged			(zoom)
   * asc_onSheetsChanged			()													- эвент на обновление списка листов
   * asc_onActiveSheetChanged		(indexActiveSheet)									- эвент на обновление активного листа
   * asc_onCanUndoChanged			(bCanUndo)											- эвент на обновление возможности undo
   * asc_onCanRedoChanged			(bCanRedo)											- эвент на обновление возможности redo
   * asc_onSaveUrl				(sUrl, callback(hasError))							- эвент на сохранение файла на сервер по url
   * asc_onDocumentModifiedChanged(bIsModified)										- эвент на обновление статуса "изменен ли файл"
   * asc_onMouseMove				(asc_CMouseMoveData)								- эвент на наведение мышкой на гиперлинк или комментарий
   * asc_onHyperlinkClick			(sUrl)												- эвент на нажатие гиперлинка
   * asc_onCoAuthoringDisconnect	()													- эвент об отключении от сервера без попытки reconnect
   * asc_onSelectionRangeChanged	(selectRange)										- эвент о выборе диапазона для диаграммы (после нажатия кнопки выбора)
   * asc_onRenameCellTextEnd		(countCellsFind, countCellsReplace)					- эвент об окончании замены текста в ячейках (мы не можем сразу прислать ответ)
   * asc_onWorkbookLocked			(result)											- эвент залочена ли работа с листами или нет
   * asc_onWorksheetLocked		(index, result)										- эвент залочен ли лист или нет
   * asc_onGetEditorPermissions	(permission)										- эвент о правах редактора
   * asc_onStopFormatPainter		()													- эвент об окончании форматирования по образцу
   * asc_onUpdateSheetViewSettings	()													- эвент об обновлении свойств листа (закрепленная область, показывать сетку/заголовки)
   * asc_onUpdateTabColor			(index)												- эвент об обновлении цвета иконки листа
   * asc_onDocumentCanSaveChanged	(bIsCanSave)										- эвент об обновлении статуса "можно ли сохранять файл"
   * asc_onDocumentUpdateVersion	(callback)											- эвент о том, что файл собрался и не может больше редактироваться
   * asc_onContextMenu			(event)												- эвент на контекстное меню
   * asc_onDocumentContentReady ()                        - эвент об окончании загрузки документа
   * asc_onFilterInfo	        (countFilter, countRecords)								- send count filtered and all records
   * asc_onLockDocumentProps/asc_onUnLockDocumentProps    - эвент о том, что залочены опции layout
   * asc_onUpdateDocumentProps                            - эвент о том, что необходимо обновить данные во вкладке layout
   */

  spreadsheet_api.prototype.asc_registerCallback = function(name, callback, replaceOldCallback) {
    this.handlers.add(name, callback, replaceOldCallback);
    return;

    /*
     Не самая хорошая схема для отправки эвентов:
     проверяем, подписан ли кто-то на эвент? Если да, то отправляем и больше ничего не делаем.
     Если никто не подписан, то сохраняем у себя переменную и как только кто-то подписывается - отправляем ее
     */
    if (null !== this._gui_control_colors && "asc_onSendThemeColors" === name) {
      this.handlers.trigger("asc_onSendThemeColors", this._gui_control_colors.Colors, this._gui_control_colors.StandartColors);
      this._gui_control_colors = null;
    }
  };

  spreadsheet_api.prototype.asc_unregisterCallback = function(name, callback) {
    this.handlers.remove(name, callback);
  };

  spreadsheet_api.prototype.asc_SetDocumentPlaceChangedEnabled = function(val) {
    this.wb.setDocumentPlaceChangedEnabled(val);
  };

  spreadsheet_api.prototype.asc_SetFastCollaborative = function(bFast) {
    if (this.collaborativeEditing) {
      AscCommon.CollaborativeEditing.Set_Fast(bFast);
      this.collaborativeEditing.setFast(bFast);
    }
  };

	spreadsheet_api.prototype.asc_setThumbnailStylesSizes = function (width, height) {
		this.styleThumbnailWidth = width;
		this.styleThumbnailHeight = height;
	};

  // Посылает эвент о том, что обновились листы
  spreadsheet_api.prototype.sheetsChanged = function() {
    this.handlers.trigger("asc_onSheetsChanged");
  };

  spreadsheet_api.prototype.asyncFontsDocumentStartLoaded = function() {
    this.OpenDocumentProgress.Type = c_oAscAsyncAction.LoadDocumentFonts;
    this.OpenDocumentProgress.FontsCount = this.FontLoader.fonts_loading.length;
    this.OpenDocumentProgress.CurrentFont = 0;
    this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);
  };

  spreadsheet_api.prototype.asyncFontsDocumentEndLoaded = function() {
    this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);

    if (this.asyncMethodCallback !== undefined) {
      this.asyncMethodCallback();
      this.asyncMethodCallback = undefined;
    } else {
      // Шрифты загрузились, возможно стоит подождать совместное редактирование
      this.FontLoadWaitComplete = true;
        this._openDocumentEndCallback();
      }
  };

  spreadsheet_api.prototype.asyncFontEndLoaded = function(font) {
    this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
  };

  spreadsheet_api.prototype._loadFonts = function(fonts, callback) {
    if (window["NATIVE_EDITOR_ENJINE"]) {
      return callback();
    }
    this.asyncMethodCallback = callback;
    var arrLoadFonts = [];
    for (var i in fonts)
      arrLoadFonts.push(new AscFonts.CFont(i, 0, "", 0));
    AscFonts.FontPickerByCharacter.extendFonts(arrLoadFonts);
    this.FontLoader.LoadDocumentFonts2(arrLoadFonts);
  };

  spreadsheet_api.prototype.openDocument = function(sData) {
    var t = this;
	this._openDocument(sData);
	this.openDocumentFromZip(this.wbModel, AscCommon.g_oDocumentUrls.getUrl('Editor.xlsx')).then(function() {
		g_oIdCounter.Set_Load(false);
		AscCommon.checkCultureInfoFontPicker();
		AscCommonExcel.asc_CStylesPainter.prototype.asc_checkStylesNames(t.wbModel.CellStyles);
		t.FontLoader.LoadDocumentFonts(t.wbModel.generateFontMap2());

		// Какая-то непонятная заглушка, чтобы не падало в ipad
		if (t.isMobileVersion) {
			AscCommon.AscBrowser.isSafariMacOs = false;
			AscCommon.PasteElementsId.PASTE_ELEMENT_ID = "wrd_pastebin";
			AscCommon.PasteElementsId.ELEMENT_DISPAY_STYLE = "none";
		}
	}).catch(function(err) {
		if (window.console && window.console.log) {
			window.console.log(err);
		}
		t.sendEvent('asc_onError', c_oAscError.ID.Unknown, c_oAscError.Level.Critical);
	});
  };
	spreadsheet_api.prototype.openDocumentFromZip = function (wb, opt_url, opt_path) {
		var t = this;
		return new Promise(function (resolve, reject) {
			var openXml = AscCommon.openXml;
			//open cache xlsx instead of documentUrl, to support pivot in xls, ods... and don't send jwt signature
			if (t.isChartEditor) {
				resolve();
				return;
			}
			var processData = function (err, data, path) {
				var nextPromise;
				if (!err && (data || path)) {
					openXml.SaxParserDataTransfer.wb = wb;
					var doc = new openXml.OpenXmlPackage();
					var wbPart = null;
					var wbXml = null;
					var pivotCaches = {};
					var jsZipWrapper = new AscCommon.JSZipWrapper();
					nextPromise = jsZipWrapper.loadAsync(data || path).then(function (zip) {
						return doc.openFromZip(zip);
					}).then(function () {
						wbPart = doc.getPartByRelationshipType(openXml.relationshipTypes.workbook);
						return wbPart.getDocumentContent();
					}).then(function (contentWorkbook) {
						wbXml = new AscCommonExcel.CT_Workbook();
						new openXml.SaxParserBase().parse(contentWorkbook, wbXml);
						if (wbXml.pivotCaches) {
							return wbXml.pivotCaches.reduce(function (prevVal, wbPivotCacheXml) {
								var pivotTableCacheDefinitionPart;
								var pivotTableCacheDefinition;
								return prevVal.then(function () {
									if (null !== wbPivotCacheXml.cacheId && null !== wbPivotCacheXml.id) {
										pivotTableCacheDefinitionPart = wbPart.getPartById(wbPivotCacheXml.id);
										return pivotTableCacheDefinitionPart.getDocumentContent();
									}
								}).then(function (content) {
									if (content) {
										pivotTableCacheDefinition = new Asc.CT_PivotCacheDefinition();
										new openXml.SaxParserBase().parse(content, pivotTableCacheDefinition);
										if (pivotTableCacheDefinition.isValidCacheSource()) {
											pivotCaches[wbPivotCacheXml.cacheId] = pivotTableCacheDefinition;
											if (pivotTableCacheDefinition.id) {
												var partPivotTableCacheRecords = pivotTableCacheDefinitionPart.getPartById(
													pivotTableCacheDefinition.id);
												return partPivotTableCacheRecords.getDocumentContent();
											}
										}
									}
								}).then(function (content) {
									if (content) {
										var pivotTableCacheRecords = new Asc.CT_PivotCacheRecords();
										new openXml.SaxParserBase().parse(content, pivotTableCacheRecords);
										pivotTableCacheDefinition.cacheRecords = pivotTableCacheRecords;
									}
								});
							}, Promise.resolve());
						}
					}).then(function () {
						if (wbXml.sheets) {
							var wsIndex = 0;
							return wbXml.sheets.reduce(function (prevVal, wbSheetXml) {
								var wsPart;
								return prevVal.then(function () {
									if (null !== wbSheetXml.id) {
										var actions = [];
										wsPart = wbPart.getPartById(wbSheetXml.id);
										var pivotParts = wsPart.getPartsByRelationshipType(
											openXml.relationshipTypes.pivotTable);
										for (var i = 0; i < pivotParts.length; ++i) {
											actions.push(pivotParts[i].getDocumentContent());
										}
										return Promise.all(actions);
									}
								}).then(function (res) {
									if (res) {
										var ws = wb.getWorksheet(wsIndex);
										for (var i = 0; i < res.length; ++i) {
											var pivotTable = new Asc.CT_pivotTableDefinition();
											new openXml.SaxParserBase().parse(res[i], pivotTable);
											var cacheDefinition = pivotCaches[pivotTable.cacheId];
											if (cacheDefinition) {
												pivotTable.cacheDefinition = cacheDefinition;
												ws.insertPivotTable(pivotTable);
											}
										}
									}
									wsIndex++;
								});
							}, Promise.resolve());
						}
					}).catch(function (err) {
						//don't show error.(case of open xls, ods, csv)
						if (window.console && window.console.log) {
							window.console.log(err);
						}
					}).then(function () {
						jsZipWrapper.close();
					});
				} else {
					if (err) {
						if (window.console && window.console.log) {
							window.console.log(err);
						}
					}
					nextPromise = Promise.resolve();
				}
				nextPromise.then(function (err) {
					//clean up
					openXml.SaxParserDataTransfer = {};
					return Asc.ReadDefTableStyles(wb);
				}).then(resolve, reject);
			};
			if (opt_url) {
				AscCommon.getJSZipUtils().getBinaryContent(opt_url, processData);
			} else {
				processData(undefined, undefined, opt_path);
			}
		});
	};

  // Соединились с сервером
  spreadsheet_api.prototype.asyncServerIdEndLoaded = function() {
    // С сервером соединились, возможно стоит подождать загрузку шрифтов
    this.ServerIdWaitComplete = true;
      this._openDocumentEndCallback();
  };

  // Эвент о пришедщих изменениях
  spreadsheet_api.prototype.syncCollaborativeChanges = function() {
    // Для быстрого сохранения уведомлять не нужно.
    if (!this.collaborativeEditing.getFast()) {
      this.handlers.trigger("asc_onCollaborativeChanges");
    }
  };

  // Применение изменений документа, пришедших при открытии
  // Их нужно применять после того, как мы создали WorkbookView
  // т.к. автофильтры, диаграммы, изображения и комментарии завязаны на WorksheetView (ToDo переделать)
  spreadsheet_api.prototype._applyFirstLoadChanges = function() {
    if (this.isDocumentLoadComplete) {
      return;
    }
    if (this.collaborativeEditing.applyChanges()) {
      // Изменений не было
      this.onDocumentContentReady();
    }
    // Пересылаем свои изменения (просто стираем чужие lock-и, т.к. своих изменений нет)
    this.collaborativeEditing.sendChanges();
  };

  /////////////////////////////////////////////////////////////////////////
  ///////////////////CoAuthoring and Chat api//////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  spreadsheet_api.prototype._coAuthoringInitEnd = function() {
    var t = this;
    this.collaborativeEditing = new AscCommonExcel.CCollaborativeEditing(/*handlers*/{
      "askLock": function() {
        t.CoAuthoringApi.askLock.apply(t.CoAuthoringApi, arguments);
      },
      "releaseLocks": function() {
        t.CoAuthoringApi.releaseLocks.apply(t.CoAuthoringApi, arguments);
      },
      "sendChanges": function() {
        t._onSaveChanges.apply(t, arguments);
      },
      "applyChanges": function() {
        t._onApplyChanges.apply(t, arguments);
      },
      "updateAfterApplyChanges": function() {
        t._onUpdateAfterApplyChanges.apply(t, arguments);
      },
      "drawSelection": function() {
        t._onDrawSelection.apply(t, arguments);
      },
      "drawFrozenPaneLines": function() {
        t._onDrawFrozenPaneLines.apply(t, arguments);
      },
      "updateAllSheetsLock": function() {
        t._onUpdateAllSheetsLock.apply(t, arguments);
      },
      "showDrawingObjects": function() {
        t._onShowDrawingObjects.apply(t, arguments);
      },
      "showComments": function() {
        t._onShowComments.apply(t, arguments);
      },
      "cleanSelection": function() {
        t._onCleanSelection.apply(t, arguments);
      },
      "updateDocumentCanSave": function() {
        t._onUpdateDocumentCanSave();
      },
      "checkCommentRemoveLock": function(lockElem) {
        return t._onCheckCommentRemoveLock(lockElem);
      },
      "unlockDefName": function() {
        t._onUnlockDefName.apply(t, arguments);
      },
      "checkDefNameLock": function(lockElem) {
        return t._onCheckDefNameLock(lockElem);
      },
      "updateAllLayoutsLock": function() {
          t._onUpdateAllLayoutsLock.apply(t, arguments);
      }
    }, this.getViewMode());

    this.CoAuthoringApi.onConnectionStateChanged = function(e) {
      t.handlers.trigger("asc_onConnectionStateChanged", e);
    };
    this.CoAuthoringApi.onLocksAcquired = function(e) {
      if (t._coAuthoringCheckEndOpenDocument(t.CoAuthoringApi.onLocksAcquired, e)) {
        return;
      }

      if (2 != e["state"]) {
        var elementValue = e["blockValue"];
        var lockElem = t.collaborativeEditing.getLockByElem(elementValue, c_oAscLockTypes.kLockTypeOther);
        if (null === lockElem) {
          lockElem = new AscCommonExcel.CLock(elementValue);
          t.collaborativeEditing.addUnlock(lockElem);
        }

        var drawing, lockType = lockElem.Element["type"];
        var oldType = lockElem.getType();
        if (c_oAscLockTypes.kLockTypeOther2 === oldType || c_oAscLockTypes.kLockTypeOther3 === oldType) {
          lockElem.setType(c_oAscLockTypes.kLockTypeOther3, true);
        } else {
          lockElem.setType(c_oAscLockTypes.kLockTypeOther, true);
        }

        // Выставляем ID пользователя, залочившего данный элемент
        lockElem.setUserId(e["user"]);

        if (lockType === c_oAscLockTypeElem.Object) {
          drawing = g_oTableId.Get_ById(lockElem.Element["rangeOrObjectId"]);
          if (drawing) {
            drawing.lockType = lockElem.Type;
          }
        }

        if (t.wb) {
          // Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
          t.wb._onWSSelectionChanged();

          // Шлем update для листов
          t._onUpdateSheetsLock(lockElem);

          t._onUpdateDefinedNames(lockElem);

          //эвент о локе в меню вкладки layout
          t._onUpdateLayoutLock(lockElem);

          var ws = t.wb.getWorksheet();
          var lockSheetId = lockElem.Element["sheetId"];
          if (lockSheetId === ws.model.getId()) {
            if (lockType === c_oAscLockTypeElem.Object) {
              // Нужно ли обновлять закрепление областей
              if (t._onUpdateFrozenPane(lockElem)) {
                ws.draw();
              } else if (drawing && ws.model === drawing.worksheet) {
                if (ws.objectRender) {
                  ws.objectRender.showDrawingObjects(true);
                }
              }
            } else if (lockType === c_oAscLockTypeElem.Range || lockType === c_oAscLockTypeElem.Sheet) {
              ws.updateSelection();
            }
          } else if (-1 !== lockSheetId && 0 === lockSheetId.indexOf(AscCommonExcel.CCellCommentator.sStartCommentId)) {
            // Коммментарий
            t.handlers.trigger("asc_onLockComment", lockElem.Element["rangeOrObjectId"], e["user"]);
          }
        }
      }
    };
    this.CoAuthoringApi.onLocksReleased = function(e, bChanges) {
      if (t._coAuthoringCheckEndOpenDocument(t.CoAuthoringApi.onLocksReleased, e, bChanges)) {
        return;
      }

      var element = e["block"];
      var lockElem = t.collaborativeEditing.getLockByElem(element, c_oAscLockTypes.kLockTypeOther);
      if (null != lockElem) {
        var curType = lockElem.getType();

        var newType = c_oAscLockTypes.kLockTypeNone;
        if (curType === c_oAscLockTypes.kLockTypeOther) {
          if (true != bChanges) {
            newType = c_oAscLockTypes.kLockTypeNone;
          } else {
            newType = c_oAscLockTypes.kLockTypeOther2;
          }
        } else if (curType === c_oAscLockTypes.kLockTypeMine) {
          // Такого быть не должно
          newType = c_oAscLockTypes.kLockTypeMine;
        } else if (curType === c_oAscLockTypes.kLockTypeOther2 || curType === c_oAscLockTypes.kLockTypeOther3) {
          newType = c_oAscLockTypes.kLockTypeOther2;
        }

        if (t.wb) {
          t.wb.getWorksheet().cleanSelection();
        }

        var drawing;
        if (c_oAscLockTypes.kLockTypeNone !== newType) {
          lockElem.setType(newType, true);
        } else {
          // Удаляем из lock-ов, тот, кто правил ушел и не сохранил
          t.collaborativeEditing.removeUnlock(lockElem);
          if (!t._onCheckCommentRemoveLock(lockElem.Element)) {
            if (lockElem.Element["type"] === c_oAscLockTypeElem.Object) {
              drawing = g_oTableId.Get_ById(lockElem.Element["rangeOrObjectId"]);
              if (drawing) {
                drawing.lockType = c_oAscLockTypes.kLockTypeNone;
              }
            }
          }
        }
        if (t.wb) {
          // Шлем update для листов
          t._onUpdateSheetsLock(lockElem);
          /*снимаем лок для DefName*/
          t.handlers.trigger("asc_onLockDefNameManager",Asc.c_oAscDefinedNameReason.OK);
          //эвент о локе в меню вкладки layout
          t._onUpdateLayoutLock(lockElem);
        }
      }
    };
    this.CoAuthoringApi.onLocksReleasedEnd = function() {
      if (!t.isDocumentLoadComplete) {
        // Пока документ еще не загружен ничего не делаем
        return;
      }

      if (t.wb) {
        // Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно сбросить блокировку toolbar
        t.wb._onWSSelectionChanged();

        var worksheet = t.wb.getWorksheet();
        worksheet.cleanSelection();
        worksheet._drawSelection();
        worksheet._drawFrozenPaneLines();
        if (worksheet.objectRender) {
          worksheet.objectRender.showDrawingObjects(true);
        }
      }
    };
    this.CoAuthoringApi.onSaveChanges = function(e, userId, bFirstLoad) {
      t.collaborativeEditing.addChanges(e);
      if (!bFirstLoad && t.isDocumentLoadComplete) {
        t.syncCollaborativeChanges();
      }
    };
    this.CoAuthoringApi.onRecalcLocks = function(excelAdditionalInfo) {
      if (!excelAdditionalInfo) {
        return;
      }

      var tmpAdditionalInfo = JSON.parse(excelAdditionalInfo);
      // Это мы получили recalcIndexColumns и recalcIndexRows
      var oRecalcIndexColumns = t.collaborativeEditing.addRecalcIndex('0', tmpAdditionalInfo['indexCols']);
      var oRecalcIndexRows = t.collaborativeEditing.addRecalcIndex('1', tmpAdditionalInfo['indexRows']);

      // Теперь нужно пересчитать индексы для lock-элементов
      if (null !== oRecalcIndexColumns || null !== oRecalcIndexRows) {
        t.collaborativeEditing._recalcLockArray(c_oAscLockTypes.kLockTypeMine, oRecalcIndexColumns, oRecalcIndexRows);
        t.collaborativeEditing._recalcLockArray(c_oAscLockTypes.kLockTypeOther, oRecalcIndexColumns, oRecalcIndexRows);
      }
    };
	  };

  spreadsheet_api.prototype._onSaveChanges = function(recalcIndexColumns, recalcIndexRows, isAfterAskSave) {
    if (this.isDocumentLoadComplete) {
      var arrChanges = this.wbModel.SerializeHistory();
      var deleteIndex = History.GetDeleteIndex();
      var excelAdditionalInfo = null;
      var bCollaborative = this.collaborativeEditing.getCollaborativeEditing();
      if (bCollaborative) {
        // Пересчетные индексы добавляем только если мы не одни
        if (recalcIndexColumns || recalcIndexRows) {
          excelAdditionalInfo = {"indexCols": recalcIndexColumns, "indexRows": recalcIndexRows};
        }
      }
      if (0 < arrChanges.length || null !== deleteIndex || null !== excelAdditionalInfo) {
        this.CoAuthoringApi.saveChanges(arrChanges, deleteIndex, excelAdditionalInfo, this.canUnlockDocument2, bCollaborative);
        History.CanNotAddChanges = true;
      } else {
        this.CoAuthoringApi.unLockDocument(!!isAfterAskSave, this.canUnlockDocument2, null, bCollaborative);
      }
      this.canUnlockDocument2 = false;
    }
  };

  spreadsheet_api.prototype._onApplyChanges = function(changes, fCallback) {
    this.wbModel.DeserializeHistory(changes, fCallback);
  };

  spreadsheet_api.prototype._onUpdateAfterApplyChanges = function() {
    if (!this.isDocumentLoadComplete) {
      // При открытии после принятия изменений мы должны сбросить пересчетные индексы
      this.collaborativeEditing.clearRecalcIndex();
      this.onDocumentContentReady();
    } else if (this.wb && !window["NATIVE_EDITOR_ENJINE"]) {
      // Нужно послать 'обновить свойства' (иначе для удаления данных не обновится строка формул).
      // ToDo Возможно стоит обновлять только строку формул
      AscCommon.CollaborativeEditing.Load_Images();
      this.wb._onWSSelectionChanged();
      History.TurnOff();
      this.wb.drawWorksheet();
      History.TurnOn();
    }
  };

  spreadsheet_api.prototype._onCleanSelection = function() {
    if (this.wb) {
      this.wb.getWorksheet().cleanSelection();
    }
  };

  spreadsheet_api.prototype._onDrawSelection = function() {
    if (this.wb) {
      this.wb.getWorksheet()._drawSelection();
    }
  };

  spreadsheet_api.prototype._onDrawFrozenPaneLines = function() {
    if (this.wb) {
      this.wb.getWorksheet()._drawFrozenPaneLines();
    }
  };

	spreadsheet_api.prototype._onUpdateAllSheetsLock = function () {
		if (this.wbModel) {
			// Шлем update для листов
			this.handlers.trigger("asc_onWorkbookLocked", this.asc_isWorkbookLocked());
			var i, length, wsModel, wsIndex;
			for (i = 0, length = this.wbModel.getWorksheetCount(); i < length; ++i) {
				wsModel = this.wbModel.getWorksheet(i);
				wsIndex = wsModel.getIndex();
				this.handlers.trigger("asc_onWorksheetLocked", wsIndex, this.asc_isWorksheetLockedOrDeleted(wsIndex));
			}
		}
	};

  spreadsheet_api.prototype._onUpdateAllLayoutsLock = function () {
      var t = this;
      if (t.wbModel) {
          var i, length, wsModel, wsIndex;
          for (i = 0, length = t.wbModel.getWorksheetCount(); i < length; ++i) {
              wsModel = t.wbModel.getWorksheet(i);
              wsIndex = wsModel.getIndex();

              var isLocked = t.asc_isLayoutLocked(wsIndex);
              if (isLocked) {
                  t.handlers.trigger("asc_onLockDocumentProps", wsIndex);
              } else {
                  t.handlers.trigger("asc_onUnLockDocumentProps", wsIndex);
              }
          }
      }
  };

  spreadsheet_api.prototype._onUpdateLayoutMenu = function (nSheetId) {
      var t = this;
      if (t.wbModel) {
          var wsModel = t.wbModel.getWorksheetById(nSheetId);
          if (wsModel) {
              var wsIndex = wsModel.getIndex();
              t.handlers.trigger("asc_onUpdateDocumentProps", wsIndex);
          }
      }
  };

  spreadsheet_api.prototype._onShowDrawingObjects = function() {
    if (this.wb) {
      var ws = this.wb.getWorksheet();
      if (ws && ws.objectRender) {
        ws.objectRender.showDrawingObjects(true);
      }
    }
  };

  spreadsheet_api.prototype._onShowComments = function() {
    if (this.wb) {
      this.wb.getWorksheet().cellCommentator.drawCommentCells();
    }
  };

	spreadsheet_api.prototype._onUpdateSheetsLock = function (lockElem) {
		// Шлем update для листов, т.к. нужно залочить лист
		if (c_oAscLockTypeElem.Sheet === lockElem.Element["type"]) {
			this._onUpdateAllSheetsLock();
		} else {
			// Шлем update для листа
			var wsModel = this.wbModel.getWorksheetById(lockElem.Element["sheetId"]);
			if (wsModel) {
				var wsIndex = wsModel.getIndex();
				this.handlers.trigger("asc_onWorksheetLocked", wsIndex, this.asc_isWorksheetLockedOrDeleted(wsIndex));
			}
		}
	};

  spreadsheet_api.prototype._onUpdateLayoutLock = function(lockElem) {
      var t = this;

      var wsModel = t.wbModel.getWorksheetById(lockElem.Element["sheetId"]);
      if (wsModel) {
          var wsIndex = wsModel.getIndex();

          var isLocked = t.asc_isLayoutLocked(wsIndex);
          if(isLocked) {
			  t.handlers.trigger("asc_onLockDocumentProps", wsIndex);
          } else {
			  t.handlers.trigger("asc_onUnLockDocumentProps", wsIndex);
          }
      }
  };

  spreadsheet_api.prototype._onUpdateFrozenPane = function(lockElem) {
    return (c_oAscLockTypeElem.Object === lockElem.Element["type"] && lockElem.Element["rangeOrObjectId"] === AscCommonExcel.c_oAscLockNameFrozenPane);
  };

	spreadsheet_api.prototype._sendWorkbookStyles = function () {
		if (this.wbModel) {

			if (window["NATIVE_EDITOR_ENJINE"]) {
				// Для нативной версии (сборка и приложение) не генерируем стили
				return;
			}

			// Отправка стилей ячеек
			this.handlers.trigger("asc_onInitEditorStyles",
				this.wb.getCellStyles(this.styleThumbnailWidth, this.styleThumbnailHeight));
		}
	};

  spreadsheet_api.prototype.startCollaborationEditing = function() {
    // Начинаем совместное редактирование
    this.collaborativeEditing.startCollaborationEditing();

	  if (this.isDocumentLoadComplete) {
		  var worksheet = this.wb.getWorksheet();
		  worksheet.cleanSelection();
		  worksheet._drawSelection();
		  worksheet._drawFrozenPaneLines();
		  if (worksheet.objectRender) {
			  worksheet.objectRender.showDrawingObjects(true);
		  }
	  }
  };

  spreadsheet_api.prototype.endCollaborationEditing = function() {
    // Временно заканчиваем совместное редактирование
    this.collaborativeEditing.endCollaborationEditing();
  };

	// End Load document
	spreadsheet_api.prototype._openDocumentEndCallback = function () {
		// Не инициализируем дважды
		if (this.isDocumentLoadComplete || !this.ServerIdWaitComplete || !this.FontLoadWaitComplete) {
			return;
		}

        if (AscCommon.EncryptionWorker)
        {
            AscCommon.EncryptionWorker.init();
            if (!AscCommon.EncryptionWorker.isChangesHandled)
                return AscCommon.EncryptionWorker.handleChanges(this.collaborativeEditing.m_arrChanges, this, this._openDocumentEndCallback);
        }

		if (0 === this.wbModel.getWorksheetCount()) {
			this.sendEvent("asc_onError", c_oAscError.ID.ConvertationOpenError, c_oAscError.Level.Critical);
			return;
        }

		this.wb = new AscCommonExcel.WorkbookView(this.wbModel, this.controller, this.handlers, this.HtmlElement,
			this.topLineEditorElement, this, this.collaborativeEditing, this.fontRenderingMode);

		if (this.isMobileVersion) {
			this.wb.defaults.worksheetView.halfSelection = true;
			this.wb.defaults.worksheetView.activeCellBorderColor = new CColor(79, 158, 79);
			var _container = document.getElementById(this.HtmlElementName);
			if (_container) {
				_container.style.overflow = "hidden";
			}
			this.wb.MobileTouchManager = new AscCommonExcel.CMobileTouchManager({eventsElement: "cell_mobile_element"});
			this.wb.MobileTouchManager.Init(this);

			// input context must be created!!!
			var _areaId = AscCommon.g_inputContext.HtmlArea.id;
			var _element = document.getElementById(_areaId);
			_element.parentNode.parentNode.style.zIndex = 10;

			this.wb.MobileTouchManager.initEvents(AscCommon.g_inputContext.HtmlArea.id);
		}

		this.asc_CheckGuiControlColors();
		this.sendColorThemes(this.wbModel.theme);
		this.asc_ApplyColorScheme(false);

		this.sendStandartTextures();
		this.sendMathToMenu();

		this._applyPreOpenLocks();
		// Применяем пришедшие при открытии изменения
		this._applyFirstLoadChanges();

		// Меняем тип состояния (на никакое)
		this.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;

		// Были ошибки при открытии, посылаем предупреждение
		if (0 < this.wbModel.openErrors.length) {
			this.sendEvent('asc_onError', c_oAscError.ID.OpenWarning, c_oAscError.Level.NoCritical);
		}

		//this.asc_Resize(); // Убрал, т.к. сверху приходит resize (http://bugzilla.onlyoffice.com/show_bug.cgi?id=14680)
	};

	// Переход на диапазон в листе
	spreadsheet_api.prototype._asc_setWorksheetRange = function (val) {
		// Получаем sheet по имени
		var ranges = null, ws;
        var sheet = val.asc_getSheet();
        if (!sheet) {
			ranges = AscCommonExcel.getRangeByRef(val.asc_getLocation(), this.wbModel.getActiveWs(), true);
			if (ranges = ranges[0]) {
				ws = ranges.worksheet;
            }
        } else {
			ws = this.wbModel.getWorksheetByName(sheet);
        }
		if (!ws) {
			this.handlers.trigger("asc_onHyperlinkClick", null);
			return;
		} else if (ws.getHidden()) {
			return;
		}
		// Индекс листа
		var sheetIndex = ws.getIndex();
		// Если не совпали индекс листа и индекс текущего, то нужно сменить
		if (this.asc_getActiveWorksheetIndex() !== sheetIndex) {
			// Меняем активный лист
			this.asc_showWorksheet(sheetIndex);
		}
		var range;
		if (ranges) {
			range = ranges.bbox;
        } else {
			range = ws.getRange2(val.asc_getRange());
			if (range) {
				range = range.getBBox0();
            }
        }
		this.wb._onSetSelection(range, /*validRange*/ true);
	};

	spreadsheet_api.prototype._onSaveCallbackInner = function () {
		var t = this;
		AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();
		// Принимаем чужие изменения
		this.collaborativeEditing.applyChanges();

		this.CoAuthoringApi.onUnSaveLock = function () {
			t.CoAuthoringApi.onUnSaveLock = null;
			if (t.isForceSaveOnUserSave && t.IsUserSave) {
				t.forceSaveButtonContinue = t.forceSave();
			}

			if (t.collaborativeEditing.getCollaborativeEditing()) {
				// Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
				t.wb._onWSSelectionChanged();
			}

			t.canSave = true;
			t.IsUserSave = false;
			t.lastSaveTime = null;

			if (!t.forceSaveButtonContinue) {
				t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
			}
			// Обновляем состояние возможности сохранения документа
			t.onUpdateDocumentModified(History.Have_Changes());

			if (undefined !== window["AscDesktopEditor"]) {
				window["AscDesktopEditor"]["OnSave"]();
			}
			if (t.disconnectOnSave) {
				t.CoAuthoringApi.disconnect(t.disconnectOnSave.code, t.disconnectOnSave.reason);
				t.disconnectOnSave = null;
			}

			if (t.canUnlockDocument) {
				t._unlockDocument();
			}
		};
		// Пересылаем свои изменения
		this.collaborativeEditing.sendChanges(this.IsUserSave, true);
	};

  // Залочена ли панель для закрепления
  spreadsheet_api.prototype._isLockedTabColor = function(index, callback) {
    var sheetId = this.wbModel.getWorksheet(index).getId();
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameTabColor);
    this.collaborativeEditing.lock([lockInfo], callback);
  };
  spreadsheet_api.prototype._isLockedSparkline = function (id, callback) {
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null,
        this.asc_getActiveWorksheetId(), id);
    this.collaborativeEditing.lock([lockInfo], callback);
  };

	spreadsheet_api.prototype._isLockedPivot = function (pivotName, callback) {
		var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null,
			this.asc_getActiveWorksheetId(), pivotName);
		this.collaborativeEditing.lock([lockInfo], callback);
	};

  spreadsheet_api.prototype._addWorksheet = function (name, i) {
    var t = this;
    var addWorksheetCallback = function(res) {
      if (res) {
        t.wbModel.createWorksheet(i, name);
        t.wb.spliceWorksheet(i, 0, null);
        if (!window["NATIVE_EDITOR_ENJINE"] || window['IS_NATIVE_EDITOR'] || window['DoctRendererMode']) {
          t.asc_showWorksheet(i);
          // Посылаем callback об изменении списка листов
          t.sheetsChanged();
		}
      }
    };

    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null,
      AscCommonExcel.c_oAscLockAddSheet, AscCommonExcel.c_oAscLockAddSheet);
    this.collaborativeEditing.lock([lockInfo], addWorksheetCallback);
  };

  // Workbook interface

  spreadsheet_api.prototype.asc_getWorksheetsCount = function() {
    return this.wbModel.getWorksheetCount();
  };

  spreadsheet_api.prototype.asc_getWorksheetName = function(index) {
    return this.wbModel.getWorksheet(index).getName();
  };

  spreadsheet_api.prototype.asc_getWorksheetTabColor = function(index) {
    return this.wbModel.getWorksheet(index).getTabColor();
  };
  spreadsheet_api.prototype.asc_setWorksheetTabColor = function(index, color) {
    var t = this;
    var changeTabColorCallback = function(res) {
      if (res) {
        color = AscCommonExcel.CorrectAscColor(color);
        t.wbModel.getWorksheet(index).setTabColor(color);
      }
    };
    this._isLockedTabColor(index, changeTabColorCallback);
  };

  spreadsheet_api.prototype.asc_getActiveWorksheetIndex = function() {
    return this.wbModel.getActive();
  };

  spreadsheet_api.prototype.asc_getActiveWorksheetId = function() {
    var activeIndex = this.wbModel.getActive();
    return this.wbModel.getWorksheet(activeIndex).getId();
  };

  spreadsheet_api.prototype.asc_getWorksheetId = function(index) {
    return this.wbModel.getWorksheet(index).getId();
  };

  spreadsheet_api.prototype.asc_isWorksheetHidden = function(index) {
    return this.wbModel.getWorksheet(index).getHidden();
  };

  spreadsheet_api.prototype.asc_getDefinedNames = function(defNameListId) {
    return this.wb.getDefinedNames(defNameListId);
  };

  spreadsheet_api.prototype.asc_setDefinedNames = function(defName) {
//            return this.wb.setDefinedNames(defName);
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }
    return this.wb.editDefinedNames(null, defName);
  };

  spreadsheet_api.prototype.asc_editDefinedNames = function(oldName, newName) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }

    return this.wb.editDefinedNames(oldName, newName);
  };

  spreadsheet_api.prototype.asc_delDefinedNames = function(oldName) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }
    return this.wb.delDefinedNames(oldName);
  };

  spreadsheet_api.prototype.asc_checkDefinedName = function(checkName, scope) {
    return this.wbModel.checkDefName(checkName, scope);
  };

  spreadsheet_api.prototype.asc_getDefaultDefinedName = function() {
    return this.wb.getDefaultDefinedName();
  };

  spreadsheet_api.prototype._onUpdateDefinedNames = function(lockElem) {
//      if( lockElem.Element["subType"] == AscCommonExcel.c_oAscLockTypeElemSubType.DefinedNames ){
      if( lockElem.Element["sheetId"] == -1 && lockElem.Element["rangeOrObjectId"] != -1 && !this.collaborativeEditing.getFast() ){
          var dN = this.wbModel.dependencyFormulas.getDefNameByNodeId(lockElem.Element["rangeOrObjectId"]);
          if (dN) {
              dN.isLock = lockElem.UserId;
              this.handlers.trigger("asc_onRefreshDefNameList",dN.getAscCDefName());
          }
          this.handlers.trigger("asc_onLockDefNameManager",Asc.c_oAscDefinedNameReason.LockDefNameManager);
      }
  };

  spreadsheet_api.prototype._onUnlockDefName = function() {
    this.wb.unlockDefName();
  };

  spreadsheet_api.prototype._onCheckDefNameLock = function() {
    return this.wb._onCheckDefNameLock();
  };

  // Залочена ли работа с листом
  spreadsheet_api.prototype.asc_isWorksheetLockedOrDeleted = function(index) {
    var ws = this.wbModel.getWorksheet(index);
    var sheetId = null;
    if (null === ws || undefined === ws) {
      sheetId = this.asc_getActiveWorksheetId();
    } else {
      sheetId = ws.getId();
    }

    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
    // Проверим, редактирует ли кто-то лист
    return (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false));
  };

  // Залочена ли работа с листами
  spreadsheet_api.prototype.asc_isWorkbookLocked = function() {
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, null, null);
    // Проверим, редактирует ли кто-то лист
    return (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false));
  };

  // Залочена ли работа с листом
  spreadsheet_api.prototype.asc_isLayoutLocked = function(index) {
      var ws = this.wbModel.getWorksheet(index);
      var sheetId = null;
      if (null === ws || undefined === ws) {
          sheetId = this.asc_getActiveWorksheetId();
      } else {
          sheetId = ws.getId();
      }

      var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null, sheetId, "layoutOptions");
      // Проверим, редактирует ли кто-то лист
      return (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false));
  };

  spreadsheet_api.prototype.asc_getHiddenWorksheets = function() {
    var model = this.wbModel;
    var len = model.getWorksheetCount();
    var i, ws, res = [];

    for (i = 0; i < len; ++i) {
      ws = model.getWorksheet(i);
      if (ws.getHidden()) {
        res.push({"index": i, "name": ws.getName()});
      }
    }
    return res;
  };

  spreadsheet_api.prototype.asc_showWorksheet = function(index) {
    if (typeof index === "number" && undefined !== index && null !== index) {
      var t = this;
      var ws = this.wbModel.getWorksheet(index);
      var isHidden = ws.getHidden();
      var showWorksheetCallback = function(res) {
        if (res) {
          t.wbModel.getWorksheet(index).setHidden(false);
          t.wb.showWorksheet(index);
          if (isHidden) {
            // Посылаем callback об изменении списка листов
            t.sheetsChanged();
          }
        }
      };
      if (isHidden) {
        var sheetId = this.wbModel.getWorksheet(index).getId();
        var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
        this.collaborativeEditing.lock([lockInfo], showWorksheetCallback);
      } else {
        showWorksheetCallback(true);
      }
    }
  };

  spreadsheet_api.prototype.asc_hideWorksheet = function() {
    var t = this;
    // Колличество листов
    var countWorksheets = this.asc_getWorksheetsCount();
    // Колличество скрытых листов
    var arrHideWorksheets = this.asc_getHiddenWorksheets();
    var countHideWorksheets = arrHideWorksheets.length;
    // Вдруг остался один лист
    if (countWorksheets <= countHideWorksheets + 1) {
      return false;
    }

    var model = this.wbModel;
    // Активный лист
    var activeWorksheet = model.getActive();
    var sheetId = this.wbModel.getWorksheet(activeWorksheet).getId();
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);

    var hideWorksheetCallback = function(res) {
      if (res) {
        t.wbModel.getWorksheet(activeWorksheet).setHidden(true);
      }
    };

    this.collaborativeEditing.lock([lockInfo], hideWorksheetCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_renameWorksheet = function(name) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return false;
    }

    var i = this.wbModel.getActive();
    var sheetId = this.wbModel.getWorksheet(i).getId();
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);

    var t = this;
    var renameCallback = function(res) {
      if (res) {
        t.wbModel.getWorksheet(i).setName(name);
        t.sheetsChanged();
      } else {
        t.handlers.trigger("asc_onError", c_oAscError.ID.LockedWorksheetRename, c_oAscError.Level.NoCritical);
      }
    };

    this.collaborativeEditing.lock([lockInfo], renameCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_addWorksheet = function(name) {
    var i = this.wbModel.getActive();
    this._addWorksheet(name, i + 1);
  };

  spreadsheet_api.prototype.asc_insertWorksheet = function(name) {
    var i = this.wbModel.getActive();
    this._addWorksheet(name, i);
  };

  // Удаление листа
  spreadsheet_api.prototype.asc_deleteWorksheet = function() {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return false;
    }

    var i = this.wbModel.getActive();
    var activeSheet = this.wbModel.getWorksheet(i);
    var activeName = parserHelp.getEscapeSheetName(activeSheet.sName);
    var sheetId = activeSheet.getId();
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);

    var t = this;
    var deleteCallback = function(res) {
      if (res) {

        History.Create_NewPoint();
        History.StartTransaction();
        t.wbModel.dependencyFormulas.lockRecal();
        // Нужно проверить все диаграммы, ссылающиеся на удаляемый лист
          t.wbModel.forEach(function (ws) {
			  History.TurnOff();
			  var wsView = t.wb.getWorksheet(ws.index, true);
			  History.TurnOn();
			  ws.oDrawingOjectsManager.updateChartReferencesWidthHistory(activeName, parserHelp.getEscapeSheetName(ws.sName));
			  if (wsView && wsView.objectRender && wsView.objectRender.controller) {
				  wsView.objectRender.controller.recalculate2(true);
			  }
          });

        // Удаляем Worksheet и получаем новый активный индекс (-1 означает, что ничего не удалилось)
        var activeNow = t.wbModel.removeWorksheet(i);
        if (-1 !== activeNow) {
          t.wb.removeWorksheet(i);
          t.asc_showWorksheet(activeNow);
          // Посылаем callback об изменении списка листов
          t.sheetsChanged();
        }
        t.wbModel.dependencyFormulas.unlockRecal();
        History.EndTransaction();
      }
    };

    this.collaborativeEditing.lock([lockInfo], deleteCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_moveWorksheet = function(where) {
    var i = this.wbModel.getActive();
    var d = i < where ? +1 : -1;
    // Мы должны поместить слева от заданного значения, поэтому если идем вправо, то вычтем 1
    if (1 === d) {
      where -= 1;
    }
    History.Create_NewPoint();
    this.wb.replaceWorksheet(i, where);
    this.wbModel.replaceWorksheet(i, where);

    // Обновим текущий номер
    this.asc_showWorksheet(where);
    // Посылаем callback об изменении списка листов
    this.sheetsChanged();
  };

  spreadsheet_api.prototype.asc_copyWorksheet = function(where, newName) {
    var scale = this.asc_getZoom();
    var i = this.wbModel.getActive();

    // ToDo уйти от lock для листа при копировании
    var sheetId = this.wbModel.getWorksheet(i).getId();
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
    var t = this;
    var copyWorksheet = function(res) {
      if (res) {
        // ToDo перейти от wsViews на wsViewsId (сейчас вызываем раньше, чем в модели, т.к. там будет sortDependency
        // и cleanCellCache, который создаст уже скопированный лист(и splice сработает неправильно))
        History.Create_NewPoint();
        t.wb.copyWorksheet(i, where);
        t.wbModel.copyWorksheet(i, where, newName);
        // Делаем активным скопированный
        t.asc_showWorksheet(where);
        t.asc_setZoom(scale);
        // Посылаем callback об изменении списка листов
        t.sheetsChanged();
      }
    };

    this.collaborativeEditing.lock([lockInfo], copyWorksheet);
  };

  spreadsheet_api.prototype.asc_cleanSelection = function() {
    this.wb.getWorksheet().cleanSelection();
  };

  spreadsheet_api.prototype.asc_getZoom = function() {
    return this.wb.getZoom();
  };

  spreadsheet_api.prototype.asc_setZoom = function(scale) {
    this.wb.changeZoom(scale);
  };

  spreadsheet_api.prototype.asc_enableKeyEvents = function(isEnabled, isFromInput) {
    if (!this.isLoadFullApi) {
      this.tmpFocus = isEnabled;
      return;
    }

    if (this.wb) {
      this.wb.enableKeyEventsHandler(isEnabled);
    }

    if (isFromInput !== true && AscCommon.g_inputContext)
      AscCommon.g_inputContext.setInterfaceEnableKeyEvents(isEnabled);
  };

  spreadsheet_api.prototype.asc_IsFocus = function(bIsNaturalFocus) {
    var res = true;
	if(this.wb.cellEditor.isTopLineActive)
	{
		res = false;
	}
    else if (this.wb) 
	{
      res = this.wb.getEnableKeyEventsHandler(bIsNaturalFocus);
    }
	
    return res;
  };

  spreadsheet_api.prototype.asc_searchEnabled = function(bIsEnabled) {
  };

  spreadsheet_api.prototype.asc_findText = function(options) {
    if (window["NATIVE_EDITOR_ENJINE"]) {
      if (this.wb.findCellText(options)) {
        var ws = this.wb.getWorksheet();
        var activeCell = this.wbModel.getActiveWs().selectionRange.activeCell;
        return [ws.getCellLeftRelative(activeCell.col, 0), ws.getCellTopRelative(activeCell.row, 0)];
      }

      return null;
    }

    var d = this.wb.findCellText(options);
    this.controller.scroll(d);
    return !!d;
  };

  spreadsheet_api.prototype.asc_replaceText = function(options) {
    options.lookIn = Asc.c_oAscFindLookIn.Formulas; // При замене поиск только в формулах
    this.wb.replaceCellText(options);
  };

  spreadsheet_api.prototype.asc_endFindText = function() {
    // Нужно очистить поиск
    this.wb._cleanFindResults();
  };

  /**
   * Делает активной указанную ячейку
   * @param {String} reference  Ссылка на ячейку вида A1 или R1C1
   */
  spreadsheet_api.prototype.asc_findCell = function (reference) {
    if (this.asc_getCellEditMode()) {
      return;
    }
    var ws = this.wb.getWorksheet();
    var d = ws.findCell(reference);
    if (0 === d.length) {
      return;
    }

    // Получаем sheet по имени
    ws = d[0].getWorksheet();
    if (!ws || ws.getHidden()) {
      return;
    }
    // Индекс листа
    var sheetIndex = ws.getIndex();
    // Если не совпали индекс листа и индекс текущего, то нужно сменить
    if (this.asc_getActiveWorksheetIndex() !== sheetIndex) {
      // Меняем активный лист
      this.asc_showWorksheet(sheetIndex);
    }

    ws = this.wb.getWorksheet();
    ws.setSelection(d[0].getBBox0());
  };

	spreadsheet_api.prototype.asc_closeCellEditor = function (cancel) {
		var result = true;
		if (this.wb) {
			result = this.wb.closeCellEditor(cancel);
		}
		return result;
	};

	spreadsheet_api.prototype.asc_setR1C1Mode = function (value) {
		AscCommonExcel.g_R1C1Mode = value;
		if (this.wbModel) {
			this._onUpdateAfterApplyChanges();
			this.wb._onUpdateSelectionName(true);
        }
	};


  // Spreadsheet interface

  spreadsheet_api.prototype.asc_getColumnWidth = function() {
    var ws = this.wb.getWorksheet();
    return ws.getSelectedColumnWidthInSymbols();
  };

  spreadsheet_api.prototype.asc_setColumnWidth = function(width) {
    this.wb.getWorksheet().changeWorksheet("colWidth", width);
  };

  spreadsheet_api.prototype.asc_showColumns = function() {
    this.wb.getWorksheet().changeWorksheet("showCols");
  };

  spreadsheet_api.prototype.asc_hideColumns = function() {
    this.wb.getWorksheet().changeWorksheet("hideCols");
  };

  spreadsheet_api.prototype.asc_autoFitColumnWidth = function() {
    this.wb.getWorksheet().autoFitColumnsWidth(null);
  };

  spreadsheet_api.prototype.asc_getRowHeight = function() {
    var ws = this.wb.getWorksheet();
    return ws.getSelectedRowHeight();
  };

  spreadsheet_api.prototype.asc_setRowHeight = function(height) {
    this.wb.getWorksheet().changeWorksheet("rowHeight", height);
  };
  spreadsheet_api.prototype.asc_autoFitRowHeight = function() {
    this.wb.getWorksheet().autoFitRowHeight(null);
  };

  spreadsheet_api.prototype.asc_showRows = function() {
    this.wb.getWorksheet().changeWorksheet("showRows");
  };

  spreadsheet_api.prototype.asc_hideRows = function() {
    this.wb.getWorksheet().changeWorksheet("hideRows");
  };

  spreadsheet_api.prototype.asc_insertCells = function(options) {
    this.wb.getWorksheet().changeWorksheet("insCell", options);
  };

  spreadsheet_api.prototype.asc_deleteCells = function(options) {
    this.wb.getWorksheet().changeWorksheet("delCell", options);
  };

  spreadsheet_api.prototype.asc_mergeCells = function(options) {
    this.wb.getWorksheet().setSelectionInfo("merge", options);
  };

  spreadsheet_api.prototype.asc_sortCells = function(options) {
    this.wb.getWorksheet().setSelectionInfo("sort", options);
  };

  spreadsheet_api.prototype.asc_emptyCells = function(options) {
    this.wb.emptyCells(options);
  };

  spreadsheet_api.prototype.asc_drawDepCells = function(se) {
    /* ToDo
     if( se != AscCommonExcel.c_oAscDrawDepOptions.Clear )
     this.wb.getWorksheet().prepareDepCells(se);
     else
     this.wb.getWorksheet().cleanDepCells();*/
  };

  // Потеряем ли мы что-то при merge ячеек
  spreadsheet_api.prototype.asc_mergeCellsDataLost = function(options) {
    return this.wb.getWorksheet().getSelectionMergeInfo(options);
  };
  
  //нужно ли спрашивать пользователя о расширении диапазона
  spreadsheet_api.prototype.asc_sortCellsRangeExpand = function() {
    return this.wb.getWorksheet().getSelectionSortInfo();
  };
  
  spreadsheet_api.prototype.asc_getSheetViewSettings = function() {
    return this.wb.getWorksheet().getSheetViewSettings();
  };

	spreadsheet_api.prototype.asc_setDisplayGridlines = function (value) {
		this.wb.getWorksheet()
			.changeWorksheet("sheetViewSettings", {type: AscCH.historyitem_Worksheet_SetDisplayGridlines, value: value});
	};

	spreadsheet_api.prototype.asc_setDisplayHeadings = function (value) {
		this.wb.getWorksheet()
			.changeWorksheet("sheetViewSettings", {type: AscCH.historyitem_Worksheet_SetDisplayHeadings, value: value});
	};

  // Images & Charts

  spreadsheet_api.prototype.asc_drawingObjectsExist = function() {
    for (var i = 0; i < this.wb.model.aWorksheets.length; i++) {
      if (this.wb.model.aWorksheets[i].Drawings && this.wb.model.aWorksheets[i].Drawings.length) {
        return true;
      }
    }
    return false;
  };

  spreadsheet_api.prototype.asc_getChartObject = function(bNoLock) {		// Return new or existing chart. For image return null
    this.asc_onOpenChartFrame();
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getAscChartObject(bNoLock);
  };

  spreadsheet_api.prototype.asc_addChartDrawingObject = function(chart) {
    var ws = this.wb.getWorksheet();
    AscFonts.IsCheckSymbols = true;
    var ret = ws.objectRender.addChartDrawingObject(chart);
    AscFonts.IsCheckSymbols = false;
    this.asc_onCloseChartFrame();
    return ret;
  };

  spreadsheet_api.prototype.asc_editChartDrawingObject = function(chart) {
    var ws = this.wb.getWorksheet();
    var ret = ws.objectRender.editChartDrawingObject(chart);
    this.asc_onCloseChartFrame();
    return ret;
  };

  spreadsheet_api.prototype.asc_addImageDrawingObject = function (imageUrl) {

    var t = this;
    AscCommon.sendImgUrls(this, [imageUrl], function(data) {

      if (data && data[0])
      {
        var ws = t.wb.getWorksheet();
        ws.objectRender.addImageDrawingObject([data[0].url], null);
      }

    }, true);

  };


  spreadsheet_api.prototype.asc_AddMath = function(Type)
  {
    var t = this, fonts = {};
    fonts["Cambria Math"] = 1;
    t._loadFonts(fonts, function() {t.asc_AddMath2(Type);});
  };

  spreadsheet_api.prototype.asc_AddMath2 = function(Type)
  {
    var ws = this.wb.getWorksheet();
    ws.objectRender.addMath(Type);
  };

  spreadsheet_api.prototype.asc_SetMathProps = function(MathProps)
  {
    var ws = this.wb.getWorksheet();
    ws.objectRender.setMathProps(MathProps);
  };

  spreadsheet_api.prototype.asc_showImageFileDialog = function() {
    // ToDo заменить на общую функцию для всех
    this.asc_addImage();
  };
  spreadsheet_api.prototype._addImageUrl = function(urls) {
    var ws = this.wb.getWorksheet();
    if (ws) {
      if (this.isImageChangeUrl || this.isShapeImageChangeUrl || this.isTextArtChangeUrl) {
        ws.objectRender.editImageDrawingObject(urls[0]);
      } else {
        ws.objectRender.addImageDrawingObject(urls, null);
      }
    }
  };
    // signatures
    spreadsheet_api.prototype.asc_addSignatureLine = function (sGuid, sSigner, sSigner2, sEmail, Width, Height, sImgUrl) {
      var ws = this.wb.getWorksheet();
      if(ws && ws.objectRender){
          ws.objectRender.addSignatureLine(sGuid, sSigner, sSigner2, sEmail, Width, Height, sImgUrl);
      }
    };

    spreadsheet_api.prototype.asc_getAllSignatures = function(){
      var ret = [];
      var aSpTree = [];
		this.wbModel.forEach(function (ws) {
			for (var j = 0; j < ws.Drawings.length; ++j) {
				aSpTree.push(ws.Drawings[j].graphicObject);
			}
		});
      AscFormat.DrawingObjectsController.prototype.getAllSignatures2(ret, aSpTree);
      return ret;
    };

    spreadsheet_api.prototype.asc_CallSignatureDblClickEvent = function(sGuid){
        var allSpr = this.asc_getAllSignatures();
        for(i = 0; i < allSpr.length; ++i){
          if(allSpr[i].signatureLine && allSpr[i].signatureLine.id === sGuid){
              this.sendEvent("asc_onSignatureDblClick", sGuid, allSpr[i].extX, allSpr[i].extY);
          }
        }
    };
    //-------------------------------------------------------

    spreadsheet_api.prototype.asc_setSelectedDrawingObjectLayer = function(layerType) {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.setGraphicObjectLayer(layerType);
  };

  spreadsheet_api.prototype.asc_setSelectedDrawingObjectAlign = function(alignType) {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.setGraphicObjectAlign(alignType);
  };

  spreadsheet_api.prototype.asc_addTextArt = function(nStyle) {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.addTextArt(nStyle);
  };

  spreadsheet_api.prototype.asc_checkDataRange = function(dialogType, dataRange, fullCheck, isRows, chartType) {
    return parserHelp.checkDataRange(this.wbModel, this.wb, dialogType, dataRange, fullCheck, isRows, chartType);
  };

  // Для вставки диаграмм в Word
  spreadsheet_api.prototype.asc_getBinaryFileWriter = function() {
    return new AscCommonExcel.BinaryFileWriter(this.wbModel);
  };

  spreadsheet_api.prototype.asc_getWordChartObject = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getWordChartObject();
  };

  spreadsheet_api.prototype.asc_cleanWorksheet = function() {
    var ws = this.wb.getWorksheet();	// Для удаления данных листа и диаграмм
    if (ws.objectRender) {
      ws.objectRender.cleanWorksheet();
    }
  };

  // Выставление данных (пока используется только для MailMerge)
  spreadsheet_api.prototype.asc_setData = function(oData) {
    this.wb.getWorksheet().setData(oData);
  };
  // Получение данных
  spreadsheet_api.prototype.asc_getData = function() {
    this.asc_closeCellEditor();
    return this.wb.getWorksheet().getData();
  };

  // Cell comment interface
  spreadsheet_api.prototype.asc_addComment = function(oComment) {
  };

  spreadsheet_api.prototype.asc_changeComment = function(id, oComment) {
    if (oComment.bDocument) {
      this.wb.cellCommentator.changeComment(id, oComment);
    } else {
      var ws = this.wb.getWorksheet();
      ws.cellCommentator.changeComment(id, oComment);
    }
  };

  spreadsheet_api.prototype.asc_selectComment = function(id) {
    var ws = this.wb.getWorksheet();
    ws.cellCommentator.selectComment(id, /*bMove*/true);
  };

  spreadsheet_api.prototype.asc_showComment = function(id, bNew) {
    var ws = this.wb.getWorksheet();
    ws.cellCommentator.showCommentById(id, bNew);
  };

  spreadsheet_api.prototype.asc_findComment = function(id) {
    var ws = this.wb.getWorksheet();
    return ws.cellCommentator.findComment(id);
  };

  spreadsheet_api.prototype.asc_removeComment = function(id) {
    var ws = this.wb.getWorksheet();
    ws.cellCommentator.removeComment(id);
    this.wb.cellCommentator.removeComment(id);
  };

  spreadsheet_api.prototype.asc_showComments = function (isShowSolved) {
    this.wb.showComments(true, isShowSolved);
  };
  spreadsheet_api.prototype.asc_hideComments = function () {
    this.wb.showComments(false, false);
  };

  // Shapes
  spreadsheet_api.prototype.setStartPointHistory = function() {
    this.noCreatePoint = true;
    this.exucuteHistory = true;
    this.asc_stopSaving();
  };

  spreadsheet_api.prototype.setEndPointHistory = function() {
    this.noCreatePoint = false;
    this.exucuteHistoryEnd = true;
    this.asc_continueSaving();
  };

  spreadsheet_api.prototype.asc_startAddShape = function(sPreset) {
    this.isStartAddShape = this.controller.isShapeAction = true;
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.startTrackNewShape(sPreset);
  };

  spreadsheet_api.prototype.asc_endAddShape = function() {
    this.isStartAddShape = false;
    this.handlers.trigger("asc_onEndAddShape");
  };


    spreadsheet_api.prototype.asc_addShapeOnSheet = function(sPreset) {
        if(this.wb){
          var ws = this.wb.getWorksheet();
          if(ws && ws.objectRender){
            ws.objectRender.addShapeOnSheet(sPreset);
          }
        }
    };

  spreadsheet_api.prototype.asc_addOleObjectAction = function(sLocalUrl, sData, sApplicationId, fWidth, fHeight, nWidthPix, nHeightPix)
  {
    var _image = this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalUrl), 1);
    if (null != _image){
        var ws = this.wb.getWorksheet();
      if(ws.objectRender){
        ws.objectRender.addOleObject(fWidth, fHeight, nWidthPix, nHeightPix, sLocalUrl, sData, sApplicationId);
      }
    }
  };

  spreadsheet_api.prototype.asc_editOleObjectAction = function(bResize, oOleObject, sImageUrl, sData, nPixWidth, nPixHeight)
  {
    if (oOleObject)
    {
      var ws = this.wb.getWorksheet();
      if(ws.objectRender){
        ws.objectRender.editOleObject(oOleObject, sData, sImageUrl, nPixWidth, nPixHeight, bResize);
      }
    }
  };


    spreadsheet_api.prototype.asc_startEditCurrentOleObject = function(){
        var ws = this.wb.getWorksheet();
        if(ws && ws.objectRender){
            ws.objectRender.startEditCurrentOleObject();
        }
    };

  spreadsheet_api.prototype.asc_isAddAutoshape = function() {
    return this.isStartAddShape;
  };

  spreadsheet_api.prototype.asc_canAddShapeHyperlink = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canAddHyperlink();
  };

  spreadsheet_api.prototype.asc_canGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canGroup();
  };

  spreadsheet_api.prototype.asc_groupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    ws.objectRender.groupGraphicObjects();
  };

  spreadsheet_api.prototype.asc_canUnGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canUnGroup();
  };

  spreadsheet_api.prototype.asc_unGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    ws.objectRender.unGroupGraphicObjects();
  };

  spreadsheet_api.prototype.asc_changeShapeType = function(value) {
    this.asc_setGraphicObjectProps(new Asc.asc_CImgProperty({ShapeProperties: {type: value}}));
  };

  spreadsheet_api.prototype.asc_getGraphicObjectProps = function() {
    var ws = this.wb.getWorksheet();
    if (ws && ws.objectRender && ws.objectRender.controller) {
      return ws.objectRender.controller.getGraphicObjectProps();
    }
    return null;
  };

  spreadsheet_api.prototype.asc_setGraphicObjectProps = function(props) {

    var ws = this.wb.getWorksheet();
    var fReplaceCallback = null, sImageUrl = null;
    if(!AscCommon.isNullOrEmptyString(props.ImageUrl)){
      if(!g_oDocumentUrls.getImageLocal(props.ImageUrl)){
        sImageUrl = props.ImageUrl;
        fReplaceCallback = function(sLocalUrl){
          props.ImageUrl = sLocalUrl;
        }
      }
    }
    else if(props.ShapeProperties && props.ShapeProperties.fill && props.ShapeProperties.fill.fill &&
    !AscCommon.isNullOrEmptyString(props.ShapeProperties.fill.fill.url)){
      if(!g_oDocumentUrls.getImageLocal(props.ShapeProperties.fill.fill.url)){
        sImageUrl = props.ShapeProperties.fill.fill.url;
        fReplaceCallback = function(sLocalUrl){
          props.ShapeProperties.fill.fill.url = sLocalUrl;
        }
      }
    }
    if(fReplaceCallback) {

      if (window["AscDesktopEditor"]) {
        var firstUrl = window["AscDesktopEditor"]["LocalFileGetImageUrl"](sImageUrl);
        firstUrl = g_oDocumentUrls.getImageUrl(firstUrl);
        fReplaceCallback(firstUrl);
        ws.objectRender.setGraphicObjectProps(props);
        return;
      }

      AscCommon.sendImgUrls(this, [sImageUrl], function (data) {

        if (data && data[0]) {
          fReplaceCallback(data[0].url);
          ws.objectRender.setGraphicObjectProps(props);
        }

      }, true);
    }
    else{
      ws.objectRender.setGraphicObjectProps(props);
    }


  };

  spreadsheet_api.prototype.asc_getOriginalImageSize = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getOriginalImageSize();
  };

  spreadsheet_api.prototype.asc_setInterfaceDrawImagePlaceTextArt = function(elementId) {
    this.textArtElementId = elementId;
  };

  spreadsheet_api.prototype.asc_changeImageFromFile = function() {
    this.isImageChangeUrl = true;
    this.asc_addImage();
  };

  spreadsheet_api.prototype.asc_changeShapeImageFromFile = function(type) {
    this.isShapeImageChangeUrl = true;
    this.textureType = type;
    this.asc_addImage();
  };

  spreadsheet_api.prototype.asc_changeArtImageFromFile = function(type) {
    this.isTextArtChangeUrl = true;
    this.textureType = type;
    this.asc_addImage();
  };

  spreadsheet_api.prototype.asc_putPrLineSpacing = function(type, value) {
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.putPrLineSpacing(type, value);
  };

  spreadsheet_api.prototype.asc_putLineSpacingBeforeAfter = function(type, value) { // "type == 0" means "Before", "type == 1" means "After"
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.putLineSpacingBeforeAfter(type, value);
  };

  spreadsheet_api.prototype.asc_setDrawImagePlaceParagraph = function(element_id, props) {
    var ws = this.wb.getWorksheet();
    ws.objectRender.setDrawImagePlaceParagraph(element_id, props);
  };

    spreadsheet_api.prototype.asc_replaceLoadImageCallback = function(fCallback){
        if(this.wb){
            var ws = this.wb.getWorksheet();
            if(ws.objectRender){
                ws.objectRender.asyncImageEndLoaded = fCallback;
            }
        }
    };

  spreadsheet_api.prototype.asyncImageEndLoaded = function(_image) {
    if (this.wb) {
      var ws = this.wb.getWorksheet();
      if (ws.objectRender.asyncImageEndLoaded) {
        ws.objectRender.asyncImageEndLoaded(_image);
      }
    }
  };

  spreadsheet_api.prototype.asyncImagesDocumentEndLoaded = function() {
    if (c_oAscAdvancedOptionsAction.None === this.advancedOptionsAction && this.wb && !window["NATIVE_EDITOR_ENJINE"]) {
      var ws = this.wb.getWorksheet();
      ws.objectRender.showDrawingObjects(true);
      ws.objectRender.controller.getGraphicObjectProps();
    }
  };

  spreadsheet_api.prototype.asyncImageEndLoadedBackground = function() {
    var worksheet = this.wb.getWorksheet();
    if (worksheet && worksheet.objectRender) {
      var drawing_area = worksheet.objectRender.drawingArea;
      if (drawing_area) {
        for (var i = 0; i < drawing_area.frozenPlaces.length; ++i) {
          worksheet.objectRender.showDrawingObjects(true);
            worksheet.objectRender.controller && worksheet.objectRender.controller.getGraphicObjectProps();
        }
      }
    }
  };

  // Frozen pane
  spreadsheet_api.prototype.asc_freezePane = function () {
    this.wb.getWorksheet().freezePane();
  };

	spreadsheet_api.prototype.asc_setSparklineGroup = function (id, oSparklineGroup) {
		var t = this;
		var changeSparkline = function (res) {
			if (res) {
				var changedSparkline = g_oTableId.Get_ById(id);
				if (changedSparkline) {
					History.Create_NewPoint();
					History.StartTransaction();
					changedSparkline.set(oSparklineGroup);
					History.EndTransaction();
					t.wb._onWSSelectionChanged();
					t.wb.getWorksheet().draw();
				}
			}
		};
		this._isLockedSparkline(id, changeSparkline);
	};

    spreadsheet_api.prototype.asc_setListType = function (type, subtype) {
      var t = this;
        var sNeedFont = AscFormat.fGetFontByNumInfo(type, subtype);
      if(typeof sNeedFont === "string" && sNeedFont.length > 0){
          var t = this, fonts = {};
          fonts[sNeedFont] = 1;
          t._loadFonts(fonts, function() {t.asc_setListType2(type, subtype);});
      }
      else{
          t.asc_setListType2(type, subtype);
      }
    };
    spreadsheet_api.prototype.asc_setListType2 = function (type, subtype) {
        var oWorksheet = this.wb.getWorksheet();
        if(oWorksheet){
            if(oWorksheet.isSelectOnShape){
                return oWorksheet.objectRender.setListType(type, subtype);
            }
        }
    };

  // Cell interface
  spreadsheet_api.prototype.asc_getCellInfo = function() {
    return this.wb.getSelectionInfo();
  };

  // Получить координаты активной ячейки
  spreadsheet_api.prototype.asc_getActiveCellCoord = function() {
    var oWorksheet = this.wb.getWorksheet();
    if(oWorksheet){
      if(oWorksheet.isSelectOnShape){
        return oWorksheet.objectRender.getContextMenuPosition();
      }
      else{
          return oWorksheet.getActiveCellCoord();
      }
    }

  };

  // Получить координаты для каких-либо действий (для общей схемы)
  spreadsheet_api.prototype.asc_getAnchorPosition = function() {
    return this.asc_getActiveCellCoord();
  };

  // Получаем свойство: редактируем мы сейчас или нет
  spreadsheet_api.prototype.asc_getCellEditMode = function() {
    return this.wb ? this.wb.getCellEditMode() : false;
  };

  spreadsheet_api.prototype.asc_getIsTrackShape = function()  {
    return this.wb ? this.wb.getIsTrackShape() : false;
  };

  spreadsheet_api.prototype.asc_setCellFontName = function(fontName) {
    var t = this, fonts = {};
    fonts[fontName] = 1;
    t._loadFonts(fonts, function() {
      var ws = t.wb.getWorksheet();
      if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellFontName) {
        ws.objectRender.controller.setCellFontName(fontName);
      } else {
        t.wb.setFontAttributes("fn", fontName);
        t.wb.restoreFocus();
      }
    });
  };

  spreadsheet_api.prototype.asc_setCellFontSize = function(fontSize) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellFontSize) {
      ws.objectRender.controller.setCellFontSize(fontSize);
    } else {
      this.wb.setFontAttributes("fs", fontSize);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellBold = function(isBold) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellBold) {
      ws.objectRender.controller.setCellBold(isBold);
    } else {
      this.wb.setFontAttributes("b", isBold);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellItalic = function(isItalic) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellItalic) {
      ws.objectRender.controller.setCellItalic(isItalic);
    } else {
      this.wb.setFontAttributes("i", isItalic);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellUnderline = function(isUnderline) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellUnderline) {
      ws.objectRender.controller.setCellUnderline(isUnderline);
    } else {
      this.wb.setFontAttributes("u", isUnderline ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellStrikeout = function(isStrikeout) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellStrikeout) {
      ws.objectRender.controller.setCellStrikeout(isStrikeout);
    } else {
      this.wb.setFontAttributes("s", isStrikeout);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellSubscript = function(isSubscript) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellSubscript) {
      ws.objectRender.controller.setCellSubscript(isSubscript);
    } else {
      this.wb.setFontAttributes("fa", isSubscript ? AscCommon.vertalign_SubScript : null);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellSuperscript = function(isSuperscript) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellSuperscript) {
      ws.objectRender.controller.setCellSuperscript(isSuperscript);
    } else {
      this.wb.setFontAttributes("fa", isSuperscript ? AscCommon.vertalign_SuperScript : null);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellAlign = function(align) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellAlign) {
      ws.objectRender.controller.setCellAlign(align);
    } else {
      this.wb.getWorksheet().setSelectionInfo("a", align);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellVertAlign = function(align) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellVertAlign) {
      ws.objectRender.controller.setCellVertAlign(align);
    } else {
      this.wb.getWorksheet().setSelectionInfo("va", align);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextWrap = function(isWrapped) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextWrap) {
      ws.objectRender.controller.setCellTextWrap(isWrapped);
    } else {
      this.wb.getWorksheet().setSelectionInfo("wrap", isWrapped);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextShrink = function(isShrinked) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextShrink) {
      ws.objectRender.controller.setCellTextShrink(isShrinked);
    } else {
      this.wb.getWorksheet().setSelectionInfo("shrink", isShrinked);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextColor = function(color) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextColor) {
      ws.objectRender.controller.setCellTextColor(color);
    } else {
      if (color instanceof Asc.asc_CColor) {
        color = AscCommonExcel.CorrectAscColor(color);
        this.wb.setFontAttributes("c", color);
        this.wb.restoreFocus();
      }
    }

  };

  spreadsheet_api.prototype.asc_setCellBackgroundColor = function(color) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellBackgroundColor) {
      ws.objectRender.controller.setCellBackgroundColor(color);
    } else {
      if (color instanceof Asc.asc_CColor || null == color) {
        if (null != color) {
          color = AscCommonExcel.CorrectAscColor(color);
        }
        this.wb.getWorksheet().setSelectionInfo("bc", color);
        this.wb.restoreFocus();
      }
    }
  };

  spreadsheet_api.prototype.asc_setCellBorders = function(borders) {
    this.wb.getWorksheet().setSelectionInfo("border", borders);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_setCellFormat = function(format) {
    this.wb.setCellFormat(format);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_setCellAngle = function(angle) {

    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellAngle) {
      ws.objectRender.controller.setCellAngle(angle);
    } else {
      this.wb.getWorksheet().setSelectionInfo("angle", angle);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellStyle = function(name) {
    this.wb.getWorksheet().setSelectionInfo("style", name);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_increaseCellDigitNumbers = function() {
    this.wb.getWorksheet().setSelectionInfo("changeDigNum", +1);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_decreaseCellDigitNumbers = function() {
    this.wb.getWorksheet().setSelectionInfo("changeDigNum", -1);
    this.wb.restoreFocus();
  };

  // Увеличение размера шрифта
  spreadsheet_api.prototype.asc_increaseFontSize = function() {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.increaseFontSize) {
      ws.objectRender.controller.increaseFontSize();
    } else {
      this.wb.changeFontSize("changeFontSize", true);
      this.wb.restoreFocus();
    }
  };

  // Уменьшение размера шрифта
  spreadsheet_api.prototype.asc_decreaseFontSize = function() {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.decreaseFontSize) {
      ws.objectRender.controller.decreaseFontSize();
    } else {
      this.wb.changeFontSize("changeFontSize", false);
      this.wb.restoreFocus();
    }
  };

  // Формат по образцу
  spreadsheet_api.prototype.asc_formatPainter = function(stateFormatPainter) {
    if (this.wb) {
      this.wb.formatPainter(stateFormatPainter);
    }
  };

  spreadsheet_api.prototype.asc_showAutoComplete = function() {
    this.wb.showAutoComplete();
  };

  spreadsheet_api.prototype.asc_onMouseUp = function(event, x, y) {
    if (this.wb) {
      this.wb._onWindowMouseUpExternal(event, x, y);
    }
  };

  //

  spreadsheet_api.prototype.asc_selectFunction = function() {

  };

	spreadsheet_api.prototype.asc_insertHyperlink = function (options) {
		AscFonts.FontPickerByCharacter.checkText(options.text, this, function () {
			this.wb.insertHyperlink(options);
		});
	};

  spreadsheet_api.prototype.asc_removeHyperlink = function() {
    this.wb.removeHyperlink();
  };

  spreadsheet_api.prototype.asc_insertFormula = function(functionName, type, autoComplete) {
    this.wb.insertFormulaInEditor(functionName, type, autoComplete);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_getFormulasInfo = function() {
    return this.formulasList;
  };
  spreadsheet_api.prototype.asc_getFormulaLocaleName = function(name) {
    return AscCommonExcel.cFormulaFunctionToLocale ? AscCommonExcel.cFormulaFunctionToLocale[name] : name;
  };

  spreadsheet_api.prototype.asc_recalc = function(isRecalcWB) {
    this.wbModel.recalcWB(isRecalcWB);
  };

  spreadsheet_api.prototype.asc_setFontRenderingMode = function(mode) {
    if (mode !== this.fontRenderingMode) {
      this.fontRenderingMode = mode;
      if (this.wb) {
        this.wb.setFontRenderingMode(mode, /*isInit*/false);
      }
    }
  };

  /**
   * Режим выбора диапазона
   * @param {Asc.c_oAscSelectionDialogType} selectionDialogType
   * @param selectRange
   */
  spreadsheet_api.prototype.asc_setSelectionDialogMode = function(selectionDialogType, selectRange) {
    this.controller.setSelectionDialogMode(Asc.c_oAscSelectionDialogType.None !== selectionDialogType);
    if (this.wb) {
      this.wb._onStopFormatPainter();
      this.wb.setSelectionDialogMode(selectionDialogType, selectRange);
    }
  };

  spreadsheet_api.prototype.asc_SendThemeColors = function(colors, standart_colors) {
    this._gui_control_colors = { Colors: colors, StandartColors: standart_colors };
    var ret = this.handlers.trigger("asc_onSendThemeColors", colors, standart_colors);
    if (false !== ret) {
      this._gui_control_colors = null;
    }
  };

	spreadsheet_api.prototype.asc_ChangeColorScheme = function (index) {
		var t = this;
		var onChangeColorScheme = function (res) {
			if (res) {
				if (t.wbModel.changeColorScheme(index)) {
					t.asc_AfterChangeColorScheme();
				}
			}
		};
		// ToDo поправить заглушку, сделать новый тип lock element-а
		var sheetId = -1; // Делаем не существующий лист и не существующий объект
		var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null, sheetId,
			sheetId);
		this.collaborativeEditing.lock([lockInfo], onChangeColorScheme);
	};
  spreadsheet_api.prototype.asc_AfterChangeColorScheme = function() {
    this.asc_CheckGuiControlColors();
    this.asc_ApplyColorScheme(true);
  };
  spreadsheet_api.prototype.asc_ApplyColorScheme = function(bRedraw) {

    if (window['IS_NATIVE_EDITOR'] || !window["NATIVE_EDITOR_ENJINE"]) {
      var wsViews = Asc["editor"].wb.wsViews;
      History.Get_RecalcData();
      for (var i = 0; i < wsViews.length; ++i) {
        if (wsViews[i] && wsViews[i].objectRender && wsViews[i].objectRender.controller) {
          wsViews[i].objectRender.controller.startRecalculate(false);
        }
      }
      this.chartPreviewManager.clearPreviews();
      this.textArtPreviewManager.clear();
    }

    // На view-режиме не нужно отправлять стили
    if (this.canEdit()) {
      // Отправка стилей
      this._sendWorkbookStyles();
    }

    if (bRedraw) {
      this.handlers.trigger("asc_onUpdateChartStyles");
      this.handlers.trigger("asc_onSelectionChanged", this.asc_getCellInfo());
      this.wb.drawWS();
    }
  };

  /////////////////////////////////////////////////////////////////////////
  ////////////////////////////AutoSave api/////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
	spreadsheet_api.prototype._autoSaveInner = function () {
		if (this.asc_getCellEditMode() || this.asc_getIsTrackShape()) {
		  return;
        }

		if (!History.Have_Changes(true) && !(this.collaborativeEditing.getCollaborativeEditing() &&
			0 !== this.collaborativeEditing.getOwnLocksLength())) {
			if (this.collaborativeEditing.getFast() && this.collaborativeEditing.haveOtherChanges()) {
				AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();

				// Принимаем чужие изменения
				this.collaborativeEditing.applyChanges();
				// Пересылаем свои изменения (просто стираем чужие lock-и, т.к. своих изменений нет)
				this.collaborativeEditing.sendChanges();
				// Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
				this.wb._onWSSelectionChanged();
			}
			return;
		}
		if (null === this.lastSaveTime) {
			this.lastSaveTime = new Date();
			return;
		}
		var saveGap = this.collaborativeEditing.getFast() ? this.autoSaveGapRealTime :
			(this.collaborativeEditing.getCollaborativeEditing() ? this.autoSaveGapSlow : this.autoSaveGapFast);
		var gap = new Date() - this.lastSaveTime - saveGap;
		if (0 <= gap) {
			this.asc_Save(true);
		}
	};

	spreadsheet_api.prototype._onUpdateDocumentCanSave = function () {
		// Можно модифицировать это условие на более быстрое (менять самим состояние в аргументах, а не запрашивать каждый раз)
		var tmp = History.Have_Changes() || (this.collaborativeEditing.getCollaborativeEditing() &&
			0 !== this.collaborativeEditing.getOwnLocksLength()) || this.asc_getCellEditMode();
		if (tmp !== this.isDocumentCanSave) {
			this.isDocumentCanSave = tmp;
			this.handlers.trigger('asc_onDocumentCanSaveChanged', this.isDocumentCanSave);
		}
	};
	spreadsheet_api.prototype._onUpdateDocumentCanUndoRedo = function () {
		AscCommon.History._sendCanUndoRedo();
	};

  spreadsheet_api.prototype._onCheckCommentRemoveLock = function(lockElem) {
    var res = false;
    var sheetId = lockElem["sheetId"];
    if (-1 !== sheetId && 0 === sheetId.indexOf(AscCommonExcel.CCellCommentator.sStartCommentId)) {
      // Коммментарий
      res = true;
      this.handlers.trigger("asc_onUnLockComment", lockElem["rangeOrObjectId"]);
    }
    return res;
  };

  spreadsheet_api.prototype.onUpdateDocumentModified = function(bIsModified) {
    // Обновляем только после окончания сохранения
    if (this.canSave) {
      this.handlers.trigger("asc_onDocumentModifiedChanged", bIsModified);
      this._onUpdateDocumentCanSave();

      if (undefined !== window["AscDesktopEditor"]) {
        window["AscDesktopEditor"]["onDocumentModifiedChanged"](bIsModified);
      }
    }
  };

	// Выставление локали
	spreadsheet_api.prototype.asc_setLocalization = function (oLocalizedData) {
		if (!this.isLoadFullApi) {
			this.tmpLocalization = oLocalizedData;
			return;
		}

		if (null == oLocalizedData) {
			AscCommonExcel.cFormulaFunctionLocalized = null;
			AscCommonExcel.cFormulaFunctionToLocale = null;
		} else {
			AscCommonExcel.cFormulaFunctionLocalized = {};
			AscCommonExcel.cFormulaFunctionToLocale = {};
			var localName;
			for (var i in AscCommonExcel.cFormulaFunction) {
				localName = oLocalizedData[i] ? oLocalizedData[i] : null;
				localName = localName ? localName : i;
				AscCommonExcel.cFormulaFunctionLocalized[localName] = AscCommonExcel.cFormulaFunction[i];
				AscCommonExcel.cFormulaFunctionToLocale[i] = localName;
			}
		}
		AscCommon.build_local_rx(oLocalizedData ? oLocalizedData["LocalFormulaOperands"] : null);
		if (this.wb) {
			this.wb.initFormulasList();
		}
		if (this.wbModel) {
			this.wbModel.rebuildColors();
		}
	};

  spreadsheet_api.prototype.asc_nativeOpenFile = function(base64File, version, isUser, xlsxPath) {
	var t = this;
    asc["editor"] = this;

    this.SpellCheckUrl = '';
 
    if (undefined == isUser) {
        this.User = new AscCommon.asc_CUser();
        this.User.setId("TM");
        this.User.setUserName("native");
    }
    if (undefined !== version) {
      AscCommon.CurFileVersion = version;
    }

    this._openDocument(base64File);
	var thenCallback = function() {
		g_oIdCounter.Set_Load(false);
		AscCommon.checkCultureInfoFontPicker();
		AscCommonExcel.asc_CStylesPainter.prototype.asc_checkStylesNames(t.wbModel.CellStyles);
		t._coAuthoringInit();
		t.wb = new AscCommonExcel.WorkbookView(t.wbModel, t.controller, t.handlers, window["_null_object"], window["_null_object"], t, t.collaborativeEditing, t.fontRenderingMode);
	};
	return this.openDocumentFromZip(this.wbModel, undefined, xlsxPath).then(thenCallback, thenCallback);
  };

  spreadsheet_api.prototype.asc_nativeCalculateFile = function() {
    window['DoctRendererMode'] = true;	
    this.wb._nativeCalculate();
  };

  spreadsheet_api.prototype.asc_nativeApplyChanges = function(changes) {
    for (var i = 0, l = changes.length; i < l; ++i) {
      this.CoAuthoringApi.onSaveChanges(changes[i], null, true);
    }
    this.collaborativeEditing.applyChanges();
  };

  spreadsheet_api.prototype.asc_nativeApplyChanges2 = function(data, isFull) {
    if (null != this.wbModel) {
      this.oRedoObjectParamNative = this.wbModel.DeserializeHistoryNative(this.oRedoObjectParamNative, data, isFull);
    }
    if (isFull) {
      this._onUpdateAfterApplyChanges();
    }
  };

  spreadsheet_api.prototype.asc_nativeGetFile = function() {
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
    return oBinaryFileWriter.Write();
  };
  spreadsheet_api.prototype.asc_nativeGetFile3 = function()
  {
      var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
      oBinaryFileWriter.Write(true, true);
      return { data: oBinaryFileWriter.Write(true, true), header: oBinaryFileWriter.WriteFileHeader(oBinaryFileWriter.Memory.GetCurPosition(), Asc.c_nVersionNoBase64) };
  };
  spreadsheet_api.prototype.asc_nativeGetFileData = function() {
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
    oBinaryFileWriter.Write(true);

    var _header = oBinaryFileWriter.WriteFileHeader(oBinaryFileWriter.Memory.GetCurPosition(), Asc.c_nVersionNoBase64);
    window["native"]["Save_End"](_header, oBinaryFileWriter.Memory.GetCurPosition());

    return oBinaryFileWriter.Memory.ImData.data;
  };
  spreadsheet_api.prototype.asc_nativeCalculate = function() {
  };

  spreadsheet_api.prototype.asc_nativePrint = function (_printer, _page, _param) {
    var _adjustPrint = window.AscDesktopEditor_PrintData || new Asc.asc_CAdjustPrint();
    window.AscDesktopEditor_PrintData = undefined;

    var isOnePage = ((_param & 0x0100) == 0x0100);
    _param &= 0xFF;
    if (1 == _param) {
      _adjustPrint.asc_setPrintType(Asc.c_oAscPrintType.EntireWorkbook);
      var pageSetup;
      var countWorksheets = this.wbModel.getWorksheetCount();
      for (var j = 0; j < countWorksheets; ++j) {
        pageSetup = this.wbModel.getWorksheet(j).PagePrintOptions.asc_getPageSetup();
        pageSetup.asc_setFitToWidth(true);
        pageSetup.asc_setFitToHeight(true);
      }
    }

    var _printPagesData = this.wb.calcPagesPrint(_adjustPrint);

    if (undefined === _printer && _page === undefined) {
      _printer = this.wb.printSheets(_printPagesData).DocumentRenderer;

      if (undefined !== window["AscDesktopEditor"]) {
        var pagescount = _printer.m_lPagesCount;

        window["AscDesktopEditor"]["Print_Start"](this.documentId + "/", pagescount, "", -1);

        for (var i = 0; i < pagescount; i++) {
          var _start = _printer.m_arrayPages[i].StartOffset;
          var _end = _printer.Memory.pos;
          if (i != (pagescount - 1)) {
            _end = _printer.m_arrayPages[i + 1].StartOffset;
          }

          window["AscDesktopEditor"]["Print_Page"](
			  _printer.Memory.GetBase64Memory2(_start, _end - _start),
			  _printer.m_arrayPages[i].Width, _printer.m_arrayPages[i].Height);
        }

        window["AscDesktopEditor"]["Print_End"]();
      }
    } else {
      this.wb.printSheets(_printPagesData, _printer);
    }

    return _printer.Memory;
  };

  spreadsheet_api.prototype.asc_nativePrintPagesCount = function() {
    return 1;
  };

  spreadsheet_api.prototype.asc_nativeGetPDF = function(_param) {
    var _ret = this.asc_nativePrint(undefined, undefined, _param);

    window["native"]["Save_End"]("", _ret.GetCurPosition());
    return _ret.data;
  };

  spreadsheet_api.prototype.asc_canPaste = function () {
    History.Create_NewPoint();
    History.StartTransaction();
    return true;
  };
  spreadsheet_api.prototype.asc_endPaste = function () {
    History.EndTransaction();
  };
  spreadsheet_api.prototype.asc_Recalculate = function () {
      History.EndTransaction();
      this._onUpdateAfterApplyChanges();
  };


  spreadsheet_api.prototype.pre_Paste = function(_fonts, _images, callback)
  {
    AscFonts.FontPickerByCharacter.extendFonts(_fonts);

    var oFontMap = {};
    for(var i = 0; i < _fonts.length; ++i){
      oFontMap[_fonts[i].name] = 1;
    }
    this._loadFonts(oFontMap, function() {

      var aImages = [];
      for(var key in _images){
        if(_images.hasOwnProperty(key)){
          aImages.push(_images[key])
        }
      }
      if(aImages.length > 0)      {
         window["Asc"]["editor"].ImageLoader.LoadDocumentImages(aImages, null);
      }
      callback();
    });
  };

  spreadsheet_api.prototype.getDefaultFontFamily = function () {
      return this.wbModel.getDefaultFont();
  };

  spreadsheet_api.prototype.getDefaultFontSize = function () {
      return this.wbModel.getDefaultSize();
  };

	spreadsheet_api.prototype._onEndLoadSdk = function () {
		AscCommon.baseEditorsApi.prototype._onEndLoadSdk.call(this);

		History = AscCommon.History;

		this.controller = new AscCommonExcel.asc_CEventsController();

		this.formulasList = AscCommonExcel.getFormulasInfo();
		this.asc_setLocale(this.tmpLocale);
		this.asc_setLocalization(this.tmpLocalization);
		this.asc_setViewMode(this.isViewMode);

        if (this.openFileCryptBinary)
        {
            window.openFileCryptCallback(this.openFileCryptBinary);
            this.openFileCryptBinary = null;
        }
	};

	spreadsheet_api.prototype.asc_OnShowContextMenu = function() {
	  this.asc_closeCellEditor();
    };

	spreadsheet_api.prototype._changePivotStyle = function (pivot, callback) {
		var t = this;
		var changePivotStyle = function (res) {
		  var ws, wsModel, pivotRange, pos, i;
			if (res) {
				wsModel = t.wbModel.getActiveWs();
				pivotRange = pivot.getRange().clone();
				for (i = 0; i < pivot.pageFieldsPositions.length; ++i) {
					pos = pivot.pageFieldsPositions[i];
					pivotRange.union3(pos.col + 1, pos.row);
				}
				History.Create_NewPoint();
				History.StartTransaction();
				callback(wsModel);
				History.EndTransaction();
				pivotRange.union2(pivot.getRange());
				// ToDo update ranges, not big range
				for (i = 0; i < pivot.pageFieldsPositions.length; ++i) {
					pos = pivot.pageFieldsPositions[i];
					pivotRange.union3(pos.col + 1, pos.row);
				}
				wsModel.updatePivotTablesStyle(pivotRange);
				ws = t.wb.getWorksheet();
				ws._onUpdateFormatTable(pivotRange);
				t.wb._onWSSelectionChanged();
				ws.draw();
			}
		};
		this._isLockedPivot(pivot.asc_getName(), changePivotStyle);
	};

	spreadsheet_api.prototype._selectSearchingResults = function () {
	  var ws = this.wbModel.getActiveWs();
	  if (ws && ws.lastFindOptions) {
	    this.wb.drawWS();
      }
	};

  /*
   * Export
   * -----------------------------------------------------------------------------
   */

  asc["spreadsheet_api"] = spreadsheet_api;
  prot = spreadsheet_api.prototype;

  prot["asc_GetFontThumbnailsPath"] = prot.asc_GetFontThumbnailsPath;
  prot["asc_setDocInfo"] = prot.asc_setDocInfo;
	prot['asc_getCurrencySymbols'] = prot.asc_getCurrencySymbols;
	prot['asc_getLocaleExample'] = prot.asc_getLocaleExample;
	prot['asc_getFormatCells'] = prot.asc_getFormatCells;
  prot["asc_getLocaleCurrency"] = prot.asc_getLocaleCurrency;
  prot["asc_setLocale"] = prot.asc_setLocale;
  prot["asc_getLocale"] = prot.asc_getLocale;
  prot["asc_getEditorPermissions"] = prot.asc_getEditorPermissions;
  prot["asc_LoadDocument"] = prot.asc_LoadDocument;
  prot["asc_DownloadAs"] = prot.asc_DownloadAs;
  prot["asc_Save"] = prot.asc_Save;
  prot["forceSave"] = prot.forceSave;
  prot["asc_setIsForceSaveOnUserSave"] = prot.asc_setIsForceSaveOnUserSave;
  prot["asc_Print"] = prot.asc_Print;
  prot["asc_Resize"] = prot.asc_Resize;
  prot["asc_Copy"] = prot.asc_Copy;
  prot["asc_Paste"] = prot.asc_Paste;
  prot["asc_SpecialPaste"] = prot.asc_SpecialPaste;
  prot["asc_Cut"] = prot.asc_Cut;
  prot["asc_Undo"] = prot.asc_Undo;
  prot["asc_Redo"] = prot.asc_Redo;

  prot["asc_getDocumentName"] = prot.asc_getDocumentName;
  prot["asc_isDocumentModified"] = prot.asc_isDocumentModified;
  prot["asc_isDocumentCanSave"] = prot.asc_isDocumentCanSave;
	prot["asc_getCanUndo"] = prot.asc_getCanUndo;
	prot["asc_getCanRedo"] = prot.asc_getCanRedo;

  prot["asc_setAutoSaveGap"] = prot.asc_setAutoSaveGap;

	prot["asc_setViewMode"] = prot.asc_setViewMode;
	prot["asc_setFilteringMode"] = prot.asc_setFilteringMode;
	prot["asc_setRestriction"] = prot.asc_setRestriction;
  prot["asc_setAdvancedOptions"] = prot.asc_setAdvancedOptions;
  prot["asc_setPageOptions"] = prot.asc_setPageOptions;
  prot["asc_savePagePrintOptions"] = prot.asc_savePagePrintOptions;
  prot["asc_getPageOptions"] = prot.asc_getPageOptions;
  prot["asc_changeDocSize"] = prot.asc_changeDocSize;
  prot["asc_changePageMargins"] = prot.asc_changePageMargins;
  prot["asc_setPageOption"] = prot.asc_setPageOption;
  prot["asc_changePageOrient"] = prot.asc_changePageOrient;

  prot["asc_decodeBuffer"] = prot.asc_decodeBuffer;

  prot["asc_registerCallback"] = prot.asc_registerCallback;
  prot["asc_unregisterCallback"] = prot.asc_unregisterCallback;

  prot["asc_changeArtImageFromFile"] = prot.asc_changeArtImageFromFile;

  prot["asc_SetDocumentPlaceChangedEnabled"] = prot.asc_SetDocumentPlaceChangedEnabled;
  prot["asc_SetFastCollaborative"] = prot.asc_SetFastCollaborative;
	prot["asc_setThumbnailStylesSizes"] = prot.asc_setThumbnailStylesSizes;

  // Workbook interface

  prot["asc_getWorksheetsCount"] = prot.asc_getWorksheetsCount;
  prot["asc_getWorksheetName"] = prot.asc_getWorksheetName;
  prot["asc_getWorksheetTabColor"] = prot.asc_getWorksheetTabColor;
  prot["asc_setWorksheetTabColor"] = prot.asc_setWorksheetTabColor;
  prot["asc_getActiveWorksheetIndex"] = prot.asc_getActiveWorksheetIndex;
  prot["asc_getActiveWorksheetId"] = prot.asc_getActiveWorksheetId;
  prot["asc_getWorksheetId"] = prot.asc_getWorksheetId;
  prot["asc_isWorksheetHidden"] = prot.asc_isWorksheetHidden;
  prot["asc_isWorksheetLockedOrDeleted"] = prot.asc_isWorksheetLockedOrDeleted;
  prot["asc_isWorkbookLocked"] = prot.asc_isWorkbookLocked;
  prot["asc_isLayoutLocked"] = prot.asc_isLayoutLocked;
  prot["asc_getHiddenWorksheets"] = prot.asc_getHiddenWorksheets;
  prot["asc_showWorksheet"] = prot.asc_showWorksheet;
  prot["asc_hideWorksheet"] = prot.asc_hideWorksheet;
  prot["asc_renameWorksheet"] = prot.asc_renameWorksheet;
  prot["asc_addWorksheet"] = prot.asc_addWorksheet;
  prot["asc_insertWorksheet"] = prot.asc_insertWorksheet;
  prot["asc_deleteWorksheet"] = prot.asc_deleteWorksheet;
  prot["asc_moveWorksheet"] = prot.asc_moveWorksheet;
  prot["asc_copyWorksheet"] = prot.asc_copyWorksheet;
  prot["asc_cleanSelection"] = prot.asc_cleanSelection;
  prot["asc_getZoom"] = prot.asc_getZoom;
  prot["asc_setZoom"] = prot.asc_setZoom;
  prot["asc_enableKeyEvents"] = prot.asc_enableKeyEvents;
  prot["asc_searchEnabled"] = prot.asc_searchEnabled;
  prot["asc_findText"] = prot.asc_findText;
  prot["asc_replaceText"] = prot.asc_replaceText;
  prot["asc_endFindText"] = prot.asc_endFindText;
  prot["asc_findCell"] = prot.asc_findCell;
  prot["asc_closeCellEditor"] = prot.asc_closeCellEditor;

  prot["asc_setR1C1Mode"] = prot.asc_setR1C1Mode;

  // Spreadsheet interface

  prot["asc_getColumnWidth"] = prot.asc_getColumnWidth;
  prot["asc_setColumnWidth"] = prot.asc_setColumnWidth;
  prot["asc_showColumns"] = prot.asc_showColumns;
  prot["asc_hideColumns"] = prot.asc_hideColumns;
  prot["asc_autoFitColumnWidth"] = prot.asc_autoFitColumnWidth;
  prot["asc_getRowHeight"] = prot.asc_getRowHeight;
  prot["asc_setRowHeight"] = prot.asc_setRowHeight;
  prot["asc_autoFitRowHeight"] = prot.asc_autoFitRowHeight;
  prot["asc_showRows"] = prot.asc_showRows;
  prot["asc_hideRows"] = prot.asc_hideRows;
  prot["asc_insertCells"] = prot.asc_insertCells;
  prot["asc_deleteCells"] = prot.asc_deleteCells;
  prot["asc_mergeCells"] = prot.asc_mergeCells;
  prot["asc_sortCells"] = prot.asc_sortCells;
  prot["asc_emptyCells"] = prot.asc_emptyCells;
  prot["asc_mergeCellsDataLost"] = prot.asc_mergeCellsDataLost;
  prot["asc_sortCellsRangeExpand"] = prot.asc_sortCellsRangeExpand;
  prot["asc_getSheetViewSettings"] = prot.asc_getSheetViewSettings;
	prot["asc_setDisplayGridlines"] = prot.asc_setDisplayGridlines;
	prot["asc_setDisplayHeadings"] = prot.asc_setDisplayHeadings;

  // Defined Names
  prot["asc_getDefinedNames"] = prot.asc_getDefinedNames;
  prot["asc_setDefinedNames"] = prot.asc_setDefinedNames;
  prot["asc_editDefinedNames"] = prot.asc_editDefinedNames;
  prot["asc_delDefinedNames"] = prot.asc_delDefinedNames;
  prot["asc_getDefaultDefinedName"] = prot.asc_getDefaultDefinedName;
  prot["asc_checkDefinedName"] = prot.asc_checkDefinedName;

  // Auto filters interface + format as table
  prot["asc_addAutoFilter"] = prot.asc_addAutoFilter;
  prot["asc_changeAutoFilter"] = prot.asc_changeAutoFilter;
  prot["asc_applyAutoFilter"] = prot.asc_applyAutoFilter;
  prot["asc_applyAutoFilterByType"] = prot.asc_applyAutoFilterByType;
  prot["asc_reapplyAutoFilter"] = prot.asc_reapplyAutoFilter;
  prot["asc_sortColFilter"] = prot.asc_sortColFilter;
  prot["asc_getAddFormatTableOptions"] = prot.asc_getAddFormatTableOptions;
  prot["asc_clearFilter"] = prot.asc_clearFilter;
  prot["asc_clearFilterColumn"] = prot.asc_clearFilterColumn;
  prot["asc_changeSelectionFormatTable"] = prot.asc_changeSelectionFormatTable;
  prot["asc_changeFormatTableInfo"] = prot.asc_changeFormatTableInfo;
  prot["asc_insertCellsInTable"] = prot.asc_insertCellsInTable;
  prot["asc_deleteCellsInTable"] = prot.asc_deleteCellsInTable;
  prot["asc_changeDisplayNameTable"] = prot.asc_changeDisplayNameTable;
  prot["asc_changeTableRange"] = prot.asc_changeTableRange;
  prot["asc_convertTableToRange"] = prot.asc_convertTableToRange;
  prot["asc_getTablePictures"] = prot.asc_getTablePictures;

  prot["asc_applyAutoCorrectOptions"] = prot.asc_applyAutoCorrectOptions;

  // Drawing objects interface

  prot["asc_showDrawingObjects"] = prot.asc_showDrawingObjects;
  prot["asc_drawingObjectsExist"] = prot.asc_drawingObjectsExist;
  prot["asc_getChartObject"] = prot.asc_getChartObject;
  prot["asc_addChartDrawingObject"] = prot.asc_addChartDrawingObject;
  prot["asc_editChartDrawingObject"] = prot.asc_editChartDrawingObject;
  prot["asc_addImageDrawingObject"] = prot.asc_addImageDrawingObject;
  prot["asc_setSelectedDrawingObjectLayer"] = prot.asc_setSelectedDrawingObjectLayer;
  prot["asc_setSelectedDrawingObjectAlign"] = prot.asc_setSelectedDrawingObjectAlign;
  prot["asc_getChartPreviews"] = prot.asc_getChartPreviews;
  prot["asc_getTextArtPreviews"] = prot.asc_getTextArtPreviews;
  prot['asc_getPropertyEditorShapes'] = prot.asc_getPropertyEditorShapes;
  prot['asc_getPropertyEditorTextArts'] = prot.asc_getPropertyEditorTextArts;
  prot["asc_checkDataRange"] = prot.asc_checkDataRange;
  prot["asc_getBinaryFileWriter"] = prot.asc_getBinaryFileWriter;
  prot["asc_getWordChartObject"] = prot.asc_getWordChartObject;
  prot["asc_cleanWorksheet"] = prot.asc_cleanWorksheet;
  prot["asc_showImageFileDialog"] = prot.asc_showImageFileDialog;
  prot["asc_addImage"] = prot.asc_addImage;
  prot["asc_setData"] = prot.asc_setData;
  prot["asc_getData"] = prot.asc_getData;
  prot["asc_onCloseChartFrame"] = prot.asc_onCloseChartFrame;

  // Cell comment interface
  prot["asc_addComment"] = prot.asc_addComment;
  prot["asc_changeComment"] = prot.asc_changeComment;
  prot["asc_findComment"] = prot.asc_findComment;
  prot["asc_removeComment"] = prot.asc_removeComment;
  prot["asc_showComment"] = prot.asc_showComment;
  prot["asc_selectComment"] = prot.asc_selectComment;

  prot["asc_showComments"] = prot.asc_showComments;
  prot["asc_hideComments"] = prot.asc_hideComments;

  // Shapes
  prot["setStartPointHistory"] = prot.setStartPointHistory;
  prot["setEndPointHistory"] = prot.setEndPointHistory;
  prot["asc_startAddShape"] = prot.asc_startAddShape;
  prot["asc_endAddShape"] = prot.asc_endAddShape;
  prot["asc_addShapeOnSheet"] = prot.asc_addShapeOnSheet;
  prot["asc_isAddAutoshape"] = prot.asc_isAddAutoshape;
  prot["asc_canAddShapeHyperlink"] = prot.asc_canAddShapeHyperlink;
  prot["asc_canGroupGraphicsObjects"] = prot.asc_canGroupGraphicsObjects;
  prot["asc_groupGraphicsObjects"] = prot.asc_groupGraphicsObjects;
  prot["asc_canUnGroupGraphicsObjects"] = prot.asc_canUnGroupGraphicsObjects;
  prot["asc_unGroupGraphicsObjects"] = prot.asc_unGroupGraphicsObjects;
  prot["asc_getGraphicObjectProps"] = prot.asc_getGraphicObjectProps;
  prot["asc_setGraphicObjectProps"] = prot.asc_setGraphicObjectProps;
  prot["asc_getOriginalImageSize"] = prot.asc_getOriginalImageSize;
  prot["asc_changeShapeType"] = prot.asc_changeShapeType;
  prot["asc_setInterfaceDrawImagePlaceShape"] = prot.asc_setInterfaceDrawImagePlaceShape;
  prot["asc_setInterfaceDrawImagePlaceTextArt"] = prot.asc_setInterfaceDrawImagePlaceTextArt;
  prot["asc_changeImageFromFile"] = prot.asc_changeImageFromFile;
  prot["asc_putPrLineSpacing"] = prot.asc_putPrLineSpacing;
  prot["asc_addTextArt"] = prot.asc_addTextArt;
  prot["asc_putLineSpacingBeforeAfter"] = prot.asc_putLineSpacingBeforeAfter;
  prot["asc_setDrawImagePlaceParagraph"] = prot.asc_setDrawImagePlaceParagraph;
  prot["asc_changeShapeImageFromFile"] = prot.asc_changeShapeImageFromFile;
  prot["asc_AddMath"] = prot.asc_AddMath;
  prot["asc_SetMathProps"] = prot.asc_SetMathProps;
  //----------------------------------------------------------------------------------------------------------------------

  // Frozen pane
  prot["asc_freezePane"] = prot.asc_freezePane;

  // Sparklines
  prot["asc_setSparklineGroup"] = prot.asc_setSparklineGroup;

  // Cell interface
  prot["asc_getCellInfo"] = prot.asc_getCellInfo;
  prot["asc_getActiveCellCoord"] = prot.asc_getActiveCellCoord;
  prot["asc_getAnchorPosition"] = prot.asc_getAnchorPosition;
  prot["asc_setCellFontName"] = prot.asc_setCellFontName;
  prot["asc_setCellFontSize"] = prot.asc_setCellFontSize;
  prot["asc_setCellBold"] = prot.asc_setCellBold;
  prot["asc_setCellItalic"] = prot.asc_setCellItalic;
  prot["asc_setCellUnderline"] = prot.asc_setCellUnderline;
  prot["asc_setCellStrikeout"] = prot.asc_setCellStrikeout;
  prot["asc_setCellSubscript"] = prot.asc_setCellSubscript;
  prot["asc_setCellSuperscript"] = prot.asc_setCellSuperscript;
  prot["asc_setCellAlign"] = prot.asc_setCellAlign;
  prot["asc_setCellVertAlign"] = prot.asc_setCellVertAlign;
  prot["asc_setCellTextWrap"] = prot.asc_setCellTextWrap;
  prot["asc_setCellTextShrink"] = prot.asc_setCellTextShrink;
  prot["asc_setCellTextColor"] = prot.asc_setCellTextColor;
  prot["asc_setCellBackgroundColor"] = prot.asc_setCellBackgroundColor;
  prot["asc_setCellBorders"] = prot.asc_setCellBorders;
  prot["asc_setCellFormat"] = prot.asc_setCellFormat;
  prot["asc_setCellAngle"] = prot.asc_setCellAngle;
  prot["asc_setCellStyle"] = prot.asc_setCellStyle;
  prot["asc_increaseCellDigitNumbers"] = prot.asc_increaseCellDigitNumbers;
  prot["asc_decreaseCellDigitNumbers"] = prot.asc_decreaseCellDigitNumbers;
  prot["asc_increaseFontSize"] = prot.asc_increaseFontSize;
  prot["asc_decreaseFontSize"] = prot.asc_decreaseFontSize;
  prot["asc_formatPainter"] = prot.asc_formatPainter;
  prot["asc_showAutoComplete"] = prot.asc_showAutoComplete;

  prot["asc_onMouseUp"] = prot.asc_onMouseUp;

  prot["asc_selectFunction"] = prot.asc_selectFunction;
  prot["asc_insertHyperlink"] = prot.asc_insertHyperlink;
  prot["asc_removeHyperlink"] = prot.asc_removeHyperlink;
  prot["asc_insertFormula"] = prot.asc_insertFormula;
  prot["asc_getFormulasInfo"] = prot.asc_getFormulasInfo;
  prot["asc_getFormulaLocaleName"] = prot.asc_getFormulaLocaleName;
  prot["asc_setFontRenderingMode"] = prot.asc_setFontRenderingMode;
  prot["asc_setSelectionDialogMode"] = prot.asc_setSelectionDialogMode;
  prot["asc_ChangeColorScheme"] = prot.asc_ChangeColorScheme;
  prot["asc_setListType"] = prot.asc_setListType;
  prot["asc_getCurrentListType"] = prot.asc_getCurrentListType;
  /////////////////////////////////////////////////////////////////////////
  ///////////////////CoAuthoring and Chat api//////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  prot["asc_coAuthoringChatSendMessage"] = prot.asc_coAuthoringChatSendMessage;
  prot["asc_coAuthoringGetUsers"] = prot.asc_coAuthoringGetUsers;
  prot["asc_coAuthoringChatGetMessages"] = prot.asc_coAuthoringChatGetMessages;
  prot["asc_coAuthoringDisconnect"] = prot.asc_coAuthoringDisconnect;

  // other
  prot["asc_stopSaving"] = prot.asc_stopSaving;
  prot["asc_continueSaving"] = prot.asc_continueSaving;

  // Version History
  prot["asc_undoAllChanges"] = prot.asc_undoAllChanges;

  prot["asc_setLocalization"] = prot.asc_setLocalization;

  // native
  prot["asc_nativeOpenFile"] = prot.asc_nativeOpenFile;
  prot["asc_nativeCalculateFile"] = prot.asc_nativeCalculateFile;
  prot["asc_nativeApplyChanges"] = prot.asc_nativeApplyChanges;
  prot["asc_nativeApplyChanges2"] = prot.asc_nativeApplyChanges2;
  prot["asc_nativeGetFile"] = prot.asc_nativeGetFile;
  prot["asc_nativeGetFileData"] = prot.asc_nativeGetFileData;
  prot["asc_nativeCalculate"] = prot.asc_nativeCalculate;
  prot["asc_nativePrint"] = prot.asc_nativePrint;
  prot["asc_nativePrintPagesCount"] = prot.asc_nativePrintPagesCount;
  prot["asc_nativeGetPDF"] = prot.asc_nativeGetPDF;
  
  prot['asc_isOffline'] = prot.asc_isOffline;
  prot['asc_getUrlType'] = prot.asc_getUrlType;

  prot['asc_getSessionToken'] = prot.asc_getSessionToken;
  // Builder
  prot['asc_nativeInitBuilder'] = prot.asc_nativeInitBuilder;
  prot['asc_SetSilentMode'] = prot.asc_SetSilentMode;

  // plugins
  prot["asc_pluginsRegister"]       = prot.asc_pluginsRegister;
  prot["asc_pluginRun"]             = prot.asc_pluginRun;
  prot["asc_pluginResize"]          = prot.asc_pluginResize;
  prot["asc_pluginButtonClick"]     = prot.asc_pluginButtonClick;
  prot["asc_addOleObject"]          = prot.asc_addOleObject;
  prot["asc_editOleObject"]         = prot.asc_editOleObject;
  prot["asc_startEditCurrentOleObject"]         = prot.asc_startEditCurrentOleObject;
  prot["asc_pluginEnableMouseEvents"] = prot.asc_pluginEnableMouseEvents;

  // system input
  prot["SetTextBoxInputMode"]       = prot.SetTextBoxInputMode;
  prot["GetTextBoxInputMode"]       = prot.GetTextBoxInputMode;

  prot["asc_InputClearKeyboardElement"] = prot.asc_InputClearKeyboardElement;

  prot["asc_OnHideContextMenu"] = prot.asc_OnHideContextMenu;
  prot["asc_OnShowContextMenu"] = prot.asc_OnShowContextMenu;

	// signatures
  prot["asc_addSignatureLine"] 		     = prot.asc_addSignatureLine;
  prot["asc_CallSignatureDblClickEvent"] = prot.asc_CallSignatureDblClickEvent;
  prot["asc_getRequestSignatures"] 	     = prot.asc_getRequestSignatures;
  prot["asc_AddSignatureLine2"]          = prot.asc_AddSignatureLine2;
  prot["asc_Sign"]             		     = prot.asc_Sign;
  prot["asc_RequestSign"]             	 = prot.asc_RequestSign;
  prot["asc_ViewCertificate"] 		     = prot.asc_ViewCertificate;
  prot["asc_SelectCertificate"] 	     = prot.asc_SelectCertificate;
  prot["asc_GetDefaultCertificate"]      = prot.asc_GetDefaultCertificate;
  prot["asc_getSignatures"] 		     = prot.asc_getSignatures;
  prot["asc_isSignaturesSupport"] 	     = prot.asc_isSignaturesSupport;
  prot["asc_isProtectionSupport"] 		 = prot.asc_isProtectionSupport;
  prot["asc_RemoveSignature"] 		= prot.asc_RemoveSignature;
  prot["asc_RemoveAllSignatures"] 	= prot.asc_RemoveAllSignatures;
  prot["asc_gotoSignature"] 	    = prot.asc_gotoSignature;
  prot["asc_getSignatureSetup"] 	= prot.asc_getSignatureSetup;

  // password
  prot["asc_setCurrentPassword"]    = prot.asc_setCurrentPassword;
  prot["asc_resetPassword"] 		= prot.asc_resetPassword;

  // mobile
  prot["asc_Remove"] = prot.asc_Remove;
})(window);
