function IsDialog()		{	return (window.dialogHeight != null);}
function IsPressCtrl()	{	return (window.event != null && window.event.ctrlKey);}
function IsPressShift()	{	return (window.event != null && (window.event.shiftLeft || window.event.shiftKey));}
function IsPressAlt()	{	return (window.event != null && (window.event.altLeft || window.event.altKey));}

function Trim(str)
{
	return str.replace(/(^\s+)|(\s+$)/g,"");
}

function ExecuteComplite(oFrame)
{
	try
	{
		var oDoc = oFrame.document.frames.Execute.document;
		if (oDoc.location.href.indexOf("://") != -1)
			ExecuteActions(oDoc.body, oFrame)
	}
	catch(e) {}
}

top.bIsSave = true;
top.bNoUnlockRecord = false;
var IsExecuteOnChangeOnProcess = false;

function ExecuteActions(oActions, oFrame)
{
	try      
	{ 
		IsExecuteOnChangeOnProcess = false;

		if (oLastDisableForm != null && (oActions == null || oActions.Refresh == null || oActions.Refresh.indexOf("Main") == -1))
			DisabledForm(oLastDisableForm, false);

		if (oActions == null)
			return;

		if (oActions.Message != null && oActions.Type != "Confirm")
		{
			if (oActions.innerText == 'Вы не можете обновить данные, т.к. с момента начала редактирования данные были изменены другим пользователем')
			{
				if (confirm("С момента начала редактирования данные были изменены другим пользователем.\r\nВы можете сохранить ваши данные, но при этом все внесенные с момента начала редактирования другим пользователем изменения будут потеряны. Сохранить ваши изменения?") == true)
				{
				    var dateNow = new Date();
					oFrame.document.forms[0].elements['__date_get_data'].value = dateNow.getDate() + "." + (dateNow.getMonth() + 1) + "." + dateNow.getFullYear() + " " + dateNow.getHours() + ":" + dateNow.getMinutes() + ":59";
					ExecOperation(oFrame.document.forms[0].all.tags("button")[0], "", "", "", "");
					return;
				}
			}
			else
				alert(oActions.innerText);
		}

		var bIsClose = IsDialog();
		if (oActions.Refresh != null)
		{
			var aRefreshs = oActions.Refresh.split(';');
			for(var nPos = 0; nPos < aRefreshs.length; nPos++)
			{
				switch(Trim(aRefreshs[nPos]))
				{
					case "Main":
					{
						var oDoc = (top.frames.DialogMainFarame != null ? top.frames.DialogMainFarame.document : top.frRight.document);
						var strURL = oDoc.location.href;
						//	Если задано что вместе с перегрузкой формы нужно обновить какие-то значения в запросе
						if (oActions.Refresh.indexOf("Value"))
						{
							var nCount = 0;
							try { nCount = parseInt(oActions.ValueCount); } catch (e) {}
							for(var nValuePos = 0; nValuePos < nCount; nValuePos++)
							{
								try
								{
									var strValueName = oActions.getAttribute("ValueName" + nValuePos);
									var strNewValue = oActions.getAttribute("NewValue" + nValuePos);
									strURL = SetURLParam(strURL, strValueName, strNewValue); 
								}
								catch (e) {}
							}
						}
						oDoc.location.href = SetURLParam(strURL, "rnd", Math.random()); 
						bIsClose = false;
						break;
					}
					case "Childs": 
					{
						var oDoc = (oFrame.document.all['data_frame'] != null ? oFrame.document.all['data_frame'] : oFrame.document);
						var strURL = (oDoc.src != null ? oDoc.src : oDoc.location.href);
						if (oFrame.SelectedRow != null)
							strURL = SetURLParam(strURL, "selected_row_index", window.SelectedRow.rowIndex);
						if (oDoc.src != null) 
							oDoc.src = strURL;
						else
							oDoc.location.href = strURL; 
						bIsClose = false; 
						break;
					}
					case "Value":
					{
						if (oFrame.document.forms == null || oFrame.document.forms[0] == null)
							continue;
						var oForm = oFrame.document.forms[0];
					
						var nCount = 0;
						try { nCount = parseInt(oActions.ValueCount); } catch (e) {}
						for(var nValuePos = 0; nValuePos < nCount; nValuePos++)
						{
							try
							{
								var strValueName = oActions.getAttribute("ValueName" + nValuePos);
								var strNewValue = oActions.getAttribute("NewValue" + nValuePos);

								//	Переделать в дальнейшем эту часть функции на вызов 
								//	SetValueToControl(oFrame.document.forms[0], strValueName, strNewValue);
								try
								{
									oElement = oForm.elements['_' + strValueName];
									if (oElement != null)
									{
										var strTagName = (oElement.length == null ? oElement.tagName.toUpperCase() : oElement[0].tagName.toUpperCase());

										if (oElement.length == null || strTagName == "SELECT" || strTagName == "OPTION")
											SetValueToSingleControl(oForm, oElement, strTagName, strValueName, strNewValue);
										else
										{
											var aValues = strNewValue.split(',');
											for(var nPos1 = 0; nPos1 < aValues.length && nPos1 < oElement.length; nPos1++)
											{
												oElement[nPos1].value = aValues[nPos1];
												SetValueToMultyEntryField(oElement[nPos1], true);
											}
										}

										if (oElement.type == "hidden" && oElement.nextSibling != null && 
										    oElement.nextSibling.preset != 'percent')
										{
											if (oElement.nextSibling.tagName.toUpperCase() == "DIV")
												oElement.nextSibling.innerText = strNewValue;
											else
												oElement.nextSibling.value = strNewValue;
										}
									}
								} 
								catch(e) {}

								try 
								{ 
									var oReadOnly = oForm.all['ro_' + strValueName];
									if (oReadOnly != null)
										oReadOnly.innerText = strNewValue; 
								} 
								catch(e) {}

								try 
								{ 
									var oFrameForList = document.frames[strValueName];
									if (oFrameForList != null)
									{
										var strOriginalURL = (oFrameForList.src != null ? oFrameForList.src : oFrameForList.location.href);
										var strURL = (strNewValue == "" ? strOriginalURL : strNewValue); 
										strURL = SetURLParam(strURL, "is_focus_list", "false");
										strURL = SetURLParam(strURL, "rnd", Math.random()); 
										if (oFrameForList.src != null)
											oFrameForList.src = strURL;
										else
											oFrameForList.location.href = strURL;
									}
								} 
								catch(e) {}
						
								if (strValueName.indexOf("is_") == 0)
									try { oForm.elements['_' + strValueName].parentElement.children[1].checked = (strNewValue.toUpperCase() == "TRUE" ? true : false); } catch(e) {}

								if (strValueName != "_date_get_data")
									top.bIsSave = false;
							}
							catch (e) {}
						}
						bIsClose = false; 
						break;
					}
					case "Parent":		top.IsRefreshParent = true; break;
					case "ParentChild":	top.IsRefreshParentChild = true; break;
					case "ParentClose":	top.IsCloseParent = true; break;
					case "WizardStep": 
					{
						try
						{ 
							bIsClose = false; 
							top.bIsDialogResized = false;
							if (oFrame.document.forms[0].elements['_wizard_step'] != null) 
								oFrame.document.forms[0].elements['_wizard_step'].value = oActions.Step; 
							oFrame.document.forms[0].elements['address_operation'].value = "";
							oFrame.document.forms[0].target = "_self";
							oFrame.document.forms[0].submit();
						} 
						catch(e) {}
						break;
					}
				}
			}
		}

		if (oActions.SetActive != null)
		{
			try
			{
				var oElement = oForm.elements['_' + oActions.SetActive];
				//	Если таких элементов на форме больше одного - то берем первый
				if (oElement.length != null)
					oElement = oElement[0];

				if (oElement.id == 'sfd')
					oElement = FindElement(oElement, 'sfd_text');
				if (oElement != null)
				{
					oLastFocusedElement = oElement;
					oElement.focus();
					oElement.select();
				}
			}
			catch (e) {}
		}

		if (oActions.Enable != null || oActions.Disable != null)
		{
			try
			{
				var bIsActionEnable = (oActions.Enable != null);
				var aNames = (bIsActionEnable? oActions.Enable : oActions.Disable).replace(/\s/gm, "").split(";");
				if (aNames.length == 1)
					aNames = aNames[0].split(",");
				for (var i = 0; i < aNames.length; i++)
				{
					var strName = aNames[i];
					var bDoEnable = bIsActionEnable;
					if (strName.charAt(0) == "-" || strName.charAt(0) == "+")
					{
						bDoEnable = (strName.charAt(0) == "+");
						strName = strName.substr(1);
					}
					EnableControl(oFrame.document.forms[0], "_" + strName, bDoEnable);
				}
			}
			catch(e) {}
			bIsClose = false;
		}

		if (oActions.SetFocus != null && oActions.SetFocus != "")
			try { oFrame.document.forms[0].elements['_' + oActions.SetFocus].focus(); } catch(e) {}

		if (oActions.Type == "Confirm")
		{
			var oResult = "";
			if (oActions.Message != null &&	confirm(oActions.innerText) == true)
				oResult = oActions.getAttribute("OkValue")
			if (oActions.DialogAddress != null)
			{
				var strDialogURL = MakeURL("/site.asmx/Dialog?address=" + oActions.DialogAddress);
				oResult = window.showModalDialog(strDialogURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
			}
			if (oResult != null && oResult != "")
			{
				var strURL = "/gate.asmx/WebExecute?" + oActions.FullURL;
				strURL = SetURLParam(strURL, "_" + oActions.ValueName, oResult);
				//	Если команда может быть выполенена как GET, то формируем URL с добавлением нового параметра
				if (oActions.FullURL != null && strURL.length < 1500)
					window.document.frames.Execute.document.location.href = strURL;
				else
				{
					//	Иначе выполняем операцию используя форму
					var oInput = oFrame.document.forms[0].elements["_" + oActions.ValueName];
					if (oInput == null)
					{
						oInput = window.document.createElement("<Input type=hidden name='_" + oActions.ValueName + "'>");
						oFrame.document.forms[0].appendChild(oInput);
					}
					oInput.value = oResult;
					//	Выбиваем из URL нужные нам параметры
					var strOperation = GetParamByUrl(strURL, "address_operation");
					var strAfterOperationAction = GetParamByUrl(strURL, "after_operation_action");
					ExecOperation(oFrame.document.forms[0].all.tags("button")[0], strOperation, "", "", strAfterOperationAction);
				}
				return;		
			}
		}

		if (oActions.IsCloseParent != null && oActions.IsCloseParent.toUpperCase() == "TRUE")
			top.IsCloseParent = true;

		if (oActions.Type == "GoTo")
		{
			var strURL = (oActions.URL == null ? SetURLParam(MakeURL("?" + oActions.Address),  "is_dialog", (IsDialog() ? "true" : "false")) : oActions.URL);
			var oWindow = (top.frames.DialogMainFarame != null ? top.frames.DialogMainFarame :  window);
			oWindow.document.location.href = SetURLParam(strURL, "rnd", Math.random());
			top.bIsDialogResized = false;
			return;
		}

		if (oActions.Type == "OpenURL")
		{
			var strURL = (oActions.URL == null ? MakeURL("/gate.asmx/WebExecute?" + oActions.Address) : oActions.URL);
			var nLeft = (oActions.Left != null ? oActions.Left : screen.width * 0.1);
			var nTop = (oActions.Top != null ? oActions.Top : screen.height * 0.1);
			var nWidth = (oActions.Width != null ? oActions.Width : screen.width * 0.8);
			var nHeight = (oActions.Height != null ? oActions.Height : screen.height * 0.8);
			window.open(strURL, "_blank", "scrollbars=yes,left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",resizable=yes");
			return;
		}

		if (oActions.Type == "Print")
		{
			var strURL = (oActions.URL == null ? MakeURL(oActions.Address) : oActions.URL);
			strURL = SetURLParam(strURL, "rnd", Math.random());
			ExecutePrint("execute_print:" + strURL);

			//	Если нужно закрываем диалог после печати
			if (oActions.AfterAction == "Close")
			{
				window.returnValue = (oActions.innerHTML != "" ? oActions.innerHTML : oActions.outerHTML); 
				window.close();
			}
			return;
		}
		
		if (oActions.Type == "OpenURL_SX")
			return ExecuteWindowSX("execute_window_sx:" + oActions.Address);

		if (oActions.Type == "Print_SX")
		{
			ExecutePrintSX("execute_print_sx:" + oActions.Address);

			//	Если нужно закрываем диалог после печати
			if (oActions.AfterAction == "Close")
			{
				window.returnValue = (oActions.innerHTML != "" ? oActions.innerHTML : oActions.outerHTML); 
				window.close();
			}
			return;
		}

		if (oActions.Type == "OpenDialog" && oActions.Address != null)
		{
			var oResult = OpenDialog("/site.asmx/Dialog?" + oActions.Address);
			AnalyzeDialogResult(oResult, window.document);
			return;
		}

		if (oActions.Type == "Close" || (oActions.Message == null && bIsClose))
		{
			window.returnValue = (oActions.innerHTML != "" ? oActions.innerHTML : oActions.outerHTML); 
			window.close();
		}
		
		if (oActions.Type == "SetPage")
		{
			SelectTabBySrc(top.TabDataSrc, oActions.Page);
			return;
		}
		
	}
	catch(e) {}
}

function EnableControl(oForm, strName, bIsEnable)
{
	try
	{
		var els = oForm.elements[strName];
		//	если els - не коллекция (противное возможно на радиокнопках), то сделаем из него массив, чтобы по нему "пробежаться"
		if (els.type != null)
			els = [els];
		for (var i = 0; i < els.length; i++)
		{
			var el = els[i];
			//	checkbox
			if (el.type == "hidden" && el.parentElement.className == "clsCheckBox" && el.nextSibling.type == "checkbox")
			{
				el = el.nextSibling;
				var elParent = el.parentElement;
				if (!bIsEnable)
				{
					elParent.onclick_orig = elParent.onclick;
					elParent.onclick = "";
				}
				else if (elParent.onclick_orig != null)
					elParent.onclick = elParent.onclick_orig;
			}
			else if (el.type == "radio")
			{
				//	radiobutton
				var elLabel = el.parentElement.nextSibling;
				if (elLabel != null && elLabel.onclick != null)
				{
					if (!bIsEnable)
					{
						elLabel.onclick_orig = elLabel.onclick;
						elLabel.onclick = "";
					}
					else if (elLabel.onclick_orig != null)
						elLabel.onclick = elLabel.onclick_orig;
				}
			}
			else if (el.type == "text")
			{
				//	text field
				if (!bIsEnable)
				{
					el.bgcolor_orig = el.style.backgroundColor;
					el.style.backgroundColor = "buttonface";
				}
				else if (el.bgcolor_orig != null)
					el.style.backgroundColor = el.bgcolor_orig;
			}

			el.disabled = !bIsEnable;
		}
	}
	catch(e) {}
}

function SetValueToControl(oForm, strValueName, strNewValue)
{
	try
	{
		var oElement = oForm.elements['_' + strValueName];

		if (oElement.length == null)
			SetValueToSingleControl(oForm, oElement, strValueName, strNewValue);
		else
		{
			var aValues = strNewValue.split(',');
			for(var nPos1 = 0; nPos1 < aValues.length && nPos1 < oElement.length; nPos1++)
				SetValueToSingleControl(oForm, oElement[nPos1], null, null, aValues[nPos1]);
		}
	}
	catch(e) {}

	try { oForm.all['ro_' + strValueName].innerText = strNewValue; } catch(e) {}
						
	if (strValueName.indexOf("is_") == 0)
		try { oForm.elements['_' + strValueName].parentElement.children[1].checked = (strNewValue.toUpperCase() == "TRUE" ? true : false); } catch(e) {}
}

function SetValueToSingleControl(oForm, oElement, strTagName, strValueName, strNewValue)
{
	try
	{
		oElement = (oElement == null && strValueName != null ? oForm.elements['_' + strValueName] : oElement);
		strTagName = (strTagName == null ? oElement.tagName.toUpperCase() : strTagName);

		switch (strTagName)
		{
			case "TEXTAREA":	oElement.innerText = strNewValue; break;
			case "SELECT":
			{
				for (var nPos = 0; nPos < oElement.options.length; nPos++)
				{
					if (oElement.options[nPos].value == strNewValue)
					{
						oElement.options[nPos].selected = true;
						break;
					} 
				}
				break;
			}
			default:			oElement.value = strNewValue; break;
		}
	} 
	catch(e) {}
}

function DialogLoadComplite()
{
	try
	{
		top.bNoUnlockRecord = false;
		var bIsIE70 = (window.navigator.appName && window.navigator.appName == "Microsoft Internet Explorer" && window.navigator.appVersion.indexOf("MSIE 7.") != -1);

		if (IsDialog() && top.bIsDialogResized != true)
		{
			var nAddWidth = parseInt(window.dialogWidth) - window.document.body.clientWidth;
			var nAddHeight = parseInt(window.dialogHeight) - window.document.body.clientHeight;

			var nDialogWidth = window.document.body.scrollWidth + nAddWidth;
			var nDialogHeight = window.document.body.scrollHeight + nAddHeight;

			if (window.document.body.MinWidth != null && nDialogWidth < window.document.body.MinWidth)
				nDialogWidth = window.document.body.MinWidth;
			if (window.document.body.MinHeight != null && nDialogHeight < window.document.body.MinHeight)
				nDialogHeight = window.document.body.MinHeight;

			if (nDialogWidth > screen.width) nDialogWidth = screen.width;
				if (nDialogHeight > screen.height) nDialogHeight = screen.height;
			if (nDialogWidth > parseInt(window.dialogWidth))
			{
				window.dialogLeft = (screen.width - nDialogWidth) / 2 + "px";
				window.dialogWidth = nDialogWidth + "px";
			}
			if (nDialogHeight > parseInt(window.dialogHeight))
			{
				window.dialogTop = (screen.height - nDialogHeight) / 2 + "px";
				window.dialogHeight = nDialogHeight + "px";
			}
			top.bIsDialogResized = true;
		}

		ListLoad();

		var strIsFocusList = GetParamByUrl(document.location.href, "is_focus_list");
		if (strIsFocusList == "true")
			window.document.focus();

		CheckEnterPosFields();
		CheckMultyFields();
		
		window.onunload = DialogClose;
		var bIsFirstFocused = (aEnterPosFields.length != 0);
		for(var nForm=0; nForm < window.document.forms.length; nForm++)
		{
			var thisForm = window.document.forms[nForm];
			for(var nElement=0; nElement < thisForm.elements.length; nElement++)
			{
				if (!bIsFirstFocused) try {thisForm[nElement].focus(); bIsFirstFocused = true;}  catch(e) {}
				thisForm[nElement].onInheritchange = thisForm[nElement].onchange;
				thisForm[nElement].onchange = DialogDataChange;
			}
		}
	}
	catch(e) {}
}

function ListLoad()
{
	try
	{
		var strIsFocusList = GetParamByUrl(document.location.href, "is_focus_list");
		if (strIsFocusList == "false")
			return;

		if (strIsFocusList == "true" || !IsDialog())
		{
			window.SelectedRow = null;
			FocusList();
		}
		else
			document.body.onfocus = FocusList;
	}
	catch(e) {}
}

function FocusList()
{
	try
	{
		if (window.SelectedRow != null || document.all['oTableData'] == null || document.all['oTableData'].rows == null)
			return;

		document.all['oTableData'].focus();
		if (window.SelectedRowIndex == null || window.SelectedRowIndex < 0 || 
				window.SelectedRowIndex > document.all['oTableData'].rows.length)
			setTimeout("SelectRow(document.all['oTableData'].rows[" + oTableHeader.rows.length + "], null);", 10);
		else
			setTimeout("SelectRow(document.all['oTableData'].rows[" + window.SelectedRowIndex + "], (window.SelectedRowIndex > 14 ? true : null));", 10);
	}
	catch(e) {}
}

var aEnterPosFields = new Array();

function CheckEnterPosFields()
{
	try
	{                 
		var aEnterFields = document.all.tags("EnterField");
		if (aEnterFields == null || aEnterFields.length == 0)
			return;

		var oForm = window.document.forms[0];
		var nPassFieldCount = 0;

		var strEnterFields = "|";
		for(var nField=0; nField < aEnterFields.length; nField++)
			if (strEnterFields.indexOf("|_" + aEnterFields[nField].name + "|") == -1)
				strEnterFields += "_" + aEnterFields[nField].name + "|";

		for(var nElement=0; nElement < oForm.elements.length; nElement++)
		{
			var oElement = oForm.elements[nElement];
			if (oElement.name == null || oElement.name == "")
				continue;
			if (strEnterFields.indexOf("|" + oElement.name + "|") == -1)
				continue;
						
			AddEnterPosField(oElement);
		}
		

		var oTop = window.dialogArguments;
		var oFocusedElement = null;
		if (oTop == null || oTop.LastEnterFieldPos == null || oTop.LastEnterFieldPos == -1 || 
			oTop.LastEnterFieldPos >= aEnterPosFields.length)
			oFocusedElement = aEnterPosFields[0];
		else
			oFocusedElement = aEnterPosFields[oTop.LastEnterFieldPos - nPassFieldCount >= 0 ? oTop.LastEnterFieldPos - nPassFieldCount : 0];

		if (oFocusedElement.tagName.toUpperCase() == "OPTION")
			oFocusedElement = oFocusedElement.parentElement;
		oFocusedElement.focus();
	}
	catch(e) {}
}

function AddEnterPosField(oElement)
{
	try
	{
		if (oElement.id == 'sfd' && oElement.tagName.toUpperCase() != "SELECT")
			oElement = FindElement(oElement, 'sfd_text');

		if (oElement.tagName != null && oElement.tagName.toUpperCase() == "INPUT" && oElement.type == "hidden")
			return;

		//	Проверяем что такого поля нет среди уже запоменных (проблемы с дублирующимися полями)
		for (var nField = 0; nField < aEnterPosFields.length; nField++)
			if (oElement == aEnterPosFields[nField])
				return;

		oElement.EnterPos = aEnterPosFields.length;
		aEnterPosFields[oElement.EnterPos] = oElement;
		oElement.onfocus = SaveLastEnterPos;
	}
	catch(e) {}
}

function CheckMultyFields()
{
	try
	{
		if (aMultyUseFields == null)
			return;

		var oForm = window.document.forms[0];
		for (var nFieldName=0; nFieldName < aMultyUseFields.length; nFieldName++)
		{
			var aEntry = oForm.elements("_" + aMultyUseFields[nFieldName]);
			if (aEntry == null)
				continue;
			for (var nEntry = 0; nEntry < aEntry.length; nEntry++)
			{
				aEntry[nEntry].disabled = (nEntry > 0);
				aEntry[nEntry].IsMultyEntry = true;
			}
		}
	}
	catch(e) {}
}

function SetValueToMultyEntryField(oActiveEntry, bIsChangeOnlyID)
{
	try
	{
		//	Если жанный контрол не используется много раз, то ничего не делаем
		if (!oActiveEntry.IsMultyEntry)
			return;

		//	Ищем все вхождение контрола с данным именем
		var aEntry = oActiveEntry.form.elements(oActiveEntry.name);
		for (var nEntry = 0; nEntry < aEntry.length; nEntry++)
		{
			//	Если это не наш контрол, то устанавливаем ему новое значение 
			if ((aEntry[nEntry] != oActiveEntry && aEntry[nEntry].value != oActiveEntry.value) || bIsChangeOnlyID)
			{
				aEntry[nEntry].value = oActiveEntry.value;
				aEntry[nEntry].old_value = aEntry[nEntry].value;
				try
				{
					if (aEntry[nEntry].id == 'sfd')
					{
						ChangeIDForSelectLong(aEntry[nEntry]);
						break;
					}
				} 
				catch(e) {}
			}
		}
	}
	catch(e) {}
}

function InitAllIFrame()
{
	try
	{
	//	Инициализируем все iframe 
		var aIFrames = document.body.all.tags('iframe');
		for(var nIFrame = 0; nIFrame < aIFrames.length; nIFrame++)
			if (aIFrames[nIFrame].data_src != null)
				aIFrames[nIFrame].src = aIFrames[nIFrame].data_src;
	}
	catch(e) {}
}

function DialogKeyPress()
{
	try
	{
		if (window.event.keyCode == 27)
			window.close();	

		if (window.event.keyCode == 13)
			MoveToNextEnterField(window.event);
	}
	catch(e) {}
}

top.LastEnterFieldPos = -1;

function SaveLastEnterPos(nValue)
{
	try
	{
		var oTop = window.dialogArguments;
		if (oTop != null != null && window.event.srcElement != null && window.event.srcElement.EnterPos != null)
			oTop.LastEnterFieldPos = (nValue == null ? window.event.srcElement.EnterPos : nValue);
	}
	catch(e) {}
}

var oEnterClickButton = null;

function MoveToNextEnterField(event)
{
	try
	{
		for(var nField = 0; nField < aEnterPosFields.length; nField++)
		{
			if (event.srcElement != aEnterPosFields[nField])
				continue;

			var oNextField = aEnterPosFields[(nField + 1 < aEnterPosFields.length ? nField + 1 : 0)];
			if (oNextField.tagName.toUpperCase() == "BUTTON")
			{
				//	Bсе по сложному, сначала через 50 мс клик на кнопке. За это время потеря фокуса отработается 
				//	и установится флаг что запрос при изменении отослан на сервер. Тогда нажатие на кнопке отработается
				//	только после того как прийдет ответ от сервера
				oEnterClickButton = oNextField;
				oEnterClickButton.focus();
				setTimeout("ClickOnFocused()", 50);
			
				window.event.cancelBubble = true;
				window.event.returnValue = false;
				return false;
			}
			else
				oNextField.focus();

			return;
		}

		//	Если этот контрол не находтится в цепочке контролов
		//	Смещаемся тогда к ближайшему находящемуся в цепочке
		var oForm = event.srcElement.form;
		if (oForm == null)
			return;
		
		// ищем позицию нашего контрола в списке контролов формы
		var nElementPos = -1;
		for (var nElement=0; nElement < oForm.elements.length; nElement++)
		{
			if (oForm[nElement] == event.srcElement)
			{
				nElementPos = nElement;
				break;
			}
		}
		if (nElementPos == -1)
			return;

		// идем по кругу начиная с нашего контрола
		for (var nPos = 0; nPos < oForm.elements.length; nPos++)
		{
			var nElement = (nElementPos + nPos < oForm.elements.length ? nElementPos + nPos : nElementPos + nPos - oForm.elements.length);
			var oElement = oForm.elements[nElement];

			//	проверяем не является ли он Enter полем
			for(var nField = 0; nField < aEnterPosFields.length; nField++)
			{
				if (oElement != aEnterPosFields[nField])
					continue;
				aEnterPosFields[nField].focus();
				return;
			}
		}

	}
	catch(e) {}
}

function ClickOnFocused()
{
	oEnterClickButton.click();
}

function ShortCutKeyUp()
{
	try
	{
		if (IsPressCtrl() && window.event.keyCode == 79) 					//Ctrl+O
		{
			ExecuteConfigurationOperation("configuration:");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 69) 	//Ctrl+Alt+E
		{
			ExecuteConfigurationOperation("configuration:Editors-DEFAULT");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 70) 	//Ctrl+Alt+F
		{
			top.oPopupEventSrc = (event != null ? event.srcElement : null);
			ExecuteConfigurationOperation("configuration:Editors-CURRENT/EditorFields-CURRENT");
			return;
		}
		if (IsPressCtrl() && window.event.keyCode == 69)   					//Ctrl+E
		{
			ExecuteConfigurationOperation("configuration:Editors");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 90)   	//Ctrl+Alt+Z
		{
			ExecuteConfigurationOperation("configuration:Relations");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 88)  	//Ctrl+Alt+X
		{
			ExecuteConfigurationOperation("configuration:Extensions");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 77)  	//Ctrl+Alt+M
		{
			ExecuteConfigurationOperation("configuration:Messages");
			return;
		}
		if (IsPressCtrl() && window.event.keyCode == 68)   					//Ctrl+D
		{
			ExecuteConfigurationOperation("configuration:ExecuteWithDebug");
			return;
		}
		if (IsPressCtrl() && window.event.keyCode == 81)   					//Ctrl+Q
		{
			ExecuteConfigurationOperation("configuration:UDIBuilder");
			return;
		}
		if (IsPressCtrl() && window.event.keyCode == 67)   					//Ctrl+C
		{
			CopyToClipboard(event.srcElement);
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 82) 	//Ctrl+Alt+R
		{
			ExecuteTableOperation("table:Refresh");
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 80) 	//Ctrl+Alt+P
		{
			var oSaved = top.oPopupEventSrc;
			top.oPopupEventSrc = { parentElement: {} };
			top.oPopupOpenerWindow.ExecuteObjectOperation("execute_function:print", true, {});
			top.oPopupEventSrc = oSaved;
			return;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 83)  	//Ctrl+Alt+S
		{
			ExecuteTableHeaderOperation("table_header:AddSort");
			return;
		}
		if (IsPressCtrl() && window.event.keyCode == 83)   					//Ctrl+S
		{
			ExecuteTableHeaderOperation("table_header:Sort");
			return;
		}
		if (IsPressAlt() && window.event.keyCode == 70)   					//Alt+F
		{
			ExecuteTableOperation("table:SetValueAsFilter");
			return false;
		}
		if (IsPressCtrl() && IsPressAlt() && window.event.keyCode == 86)  	//Ctrl+Alt+V
		{
			ExecuteJSOperation("js:ShowAllFieldValues");
			return;
		}
	}
	catch(e) {}
}

function DialogDataChange()
{
	try
	{
		window.event.srcElement.form.is_changed = 'true';
		window.event.srcElement.is_changed = 'true';
		if (window.event.srcElement.onInheritchange != null)
			window.event.srcElement.onInheritchange();
	}
	catch(e) {}
}

function DialogClose(bIsClose)
{
	try
	{
		if (!top.bIsSave)
		{
			for(var nForm=0; nForm < window.document.forms.length; nForm++)
			{
				if (window.returnValue == null && window.document.forms[nForm].is_changed == 'true' && 
					confirm('Данные были изменены. Хотите их сохранить?') == true)
				{
					window.returnValue = "";
					window.document.forms[nForm].submit();
					if (bIsClose)
						return;
					else
						alert("Данные сохранены");
				}
				else
					window.document.forms[nForm].is_changed = '';
			}
		}
	
		if (top.IsRefreshParentChild)
			window.returnValue = (window.returnValue != null ? window.returnValue : "") + "0";
		if (top.IsRefreshParent)
			window.returnValue = (window.returnValue != null ? window.returnValue : "") + " Refresh=\"Parent\"";
		if (top.IsCloseParent)
			window.returnValue = (window.returnValue != null ? window.returnValue : "") + " Close=\"Parent\"";


		if (bIsClose)
			window.close();
	}
	catch(e) {}
}

function CheckTable(oRow)
{
	var oTable = oRow;
	try
	{
		while (oTable != null && oTable.id != "oTableData")
			oTable = oTable.parentElement;
	}
	catch(e) {}

	return oTable;
}

function CheckRow(oRow)
{
	try
	{
		var oTable = CheckTable(oRow);

		if (!oTable.IsListAsCards)
		{
			var oCurRow = oRow;
			while(oCurRow != null && oCurRow.tagName.toUpperCase() != "TR" && oCurRow.tagName.toUpperCase() != "TABLE")
				oCurRow = oCurRow.parentElement;
			if (oCurRow && IsListStacked())
				oCurRow = GetRecordRows(oCurRow)[0];
			return (oCurRow != null && oCurRow.tagName.toUpperCase() == "TR" ? oCurRow : null);
		}
		else
		{
			var oLastCell = null;
			var oCurElement = oRow;

			while (oCurElement != null && oCurElement != oTable)
			{
				if (oCurElement.tagName.toUpperCase() == "TD")
					oLastCell = oCurElement;
				oCurElement = oCurElement.parentElement;
			}
			return oLastCell;
		}
	}
	catch(e) {}

	return oRow;
}

function CheckCell(oCell)
{
	try
	{
		var oCurCell = oCell;
		while(oCurCell != null && oCurCell.tagName.toUpperCase() != "TD")
			oCurCell = oCurCell.parentElement;
		return oCurCell;
	}
	catch(e) {}

	return oCell;
}

//========= Select row support functions =========================================================================

function SelectRow(oRow, bScrollIntoView)
{
	try
	{
		//	Берем текущую строку
		oRow = (oRow == null ? window.event.srcElement : oRow);
		oRow = CheckRow(oRow);
		if (IsEmptyID(oRow) && oRow.RowAddress == null)
			return;
		var oTable = CheckTable(oRow);

		if (oRow ==  null || oTable == null || 
			(window.event != null && window.event.type == "contextmenu" && IsSelected(oRow)))
			return;

		if (oTable.IsListAsCards)
			return SelectCard(oRow, oTable, bScrollIntoView);

		if (IsPressCtrl())
		{
			var oCell = window.event.srcElement;
			while(oCell != null && oCell.tagName.toUpperCase() != "TD")
				oCell = oCell.parentElement;
			if (InplaceEdit(oRow, oCell)) return;
		}

		//	Если Ctrl не нажат, то убираем все выделения
		var bRemoveAllSelect = !IsPressCtrl() && !IsPressShift();
		if (bRemoveAllSelect)
		{
			for(var nRow = 1; nRow < oTable.rows.length; nRow++)
			{ 
				if (oTable.rows[nRow] == oRow)
					continue;
				SetRowUnSelected(oTable.rows[nRow]);
			}
		}
		
		//	Если Shift нажат, то выделяем все от последнего выделения до текущей строки
		if (IsPressShift())
		{
			var nFrom = (oRow.rowIndex < oTable.selected_row.rowIndex ? oRow.rowIndex : oTable.selected_row.rowIndex);
			var nTo = (oRow.rowIndex > oTable.selected_row.rowIndex ? oRow.rowIndex : oTable.selected_row.rowIndex);
			
			for(var nRow = nFrom; nRow <= nTo; nRow++)
				SetRowSelected(oTable.rows[nRow]);
		}

		if (!IsPressCtrl() || !IsSelected(oRow))
			SetRowSelected(oRow);
		else
			SetRowUnSelected(oRow);

		window.SelectedRow = oRow;
		oTable.onkeydown = TableKeyUp;

//		try { onSelectRow(); } catch(e) {}

		if (bScrollIntoView == true) window.SelectedRow.scrollIntoView(true);
		if (bScrollIntoView == false) window.SelectedRow.scrollIntoView(false);
	}
	catch(e) {}
}

function IsSelected(oRow)
{
	return (oRow.className == 'clsRowSelected' || oRow.className == 'clsRowSelectedFocus');
}

function SetRowSelected(oRow)
{
	try
	{
		var bIsRowSelected = IsSelected(oRow);
		oTable = oRow.parentElement.parentElement;
		if (oTable != null && oTable.selected_row != null && oTable.selected_row != oRow && IsSelected(oTable.selected_row))
			SetClassForRecordRows(oTable.selected_row, "clsRowSelected", "clsRowSelectedLine2");
			
		oTable.selected_row = oRow;
		SetClassForRecordRows(oRow, "clsRowSelectedFocus", "clsRowSelectedFocusLine2");
		
		if (window.event != null && window.event.srcElement != null && 
			window.event.srcElement.tagName.toUpperCase() == "TD" &&
			IsCellInDataRow(window.event.srcElement, oRow))
			SetCellSelected(window.event.srcElement);
		else
		if (window.SelectedRowCell != null)
			SetCellSelected(FindSameCellInRow(oRow, window.SelectedRowCell));
		else
			SetCellSelected(oRow.cells[0]);

		if (bIsRowSelected)
			return;

		var oCels = oRow.cells;
		for(var nCol = 0; nCol < oRow.cells.length; nCol++)
		{
			if (oCels[nCol].style.backgroundColor != '')
			{
				oCels[nCol].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/editor/images/lock_back_light.gif', sizingMethod='crop')";
				if (oCels[nCol].style.color == null || oCels[nCol].style.color == "")
					oCels[nCol].style.color = '#000000';
			}
		}
	}
	catch(e) {}
}

function SetRowUnSelected(oRow)
{
	try
	{
		if (!IsSelected(oRow))
			return;

		SetCellUnSelected();

		oTable = oRow.parentElement.parentElement;
		if (oTable != null && oTable.selected_row == oRow)
			oTable.selected_row = null;

		SetClassForRecordRows(oRow, 'clsRowNoSelected');
		oRow.tabIndex = null;
		var oCels = oRow.cells;
		for(var nCol = 0; nCol < oCels.length; nCol++)
		{
			if (oCels[nCol].style.backgroundColor != '')
			{
				oCels[nCol].style.filter = '';
				oCels[nCol].style.color = (oCels[nCol].style.color == '#000000' ? '' : oCels[nCol].style.color);
			}
		}

	}
	catch(e) {}
}

function SelectCell(oCell)
{
	SetCellUnSelected();
	SetCellSelected(oCell);
}

function SetCellSelected(oCell)
{
	try
	{
		if (oCell == null || oCell.tagName.toUpperCase() != "TD" || window.SelectedRowCell == oCell)
			return;

		SetCellUnSelected();

		window.SelectedRowCell = oCell;
		oCell.innerHTML = "<span class=clsSelectedCell><span>" + oCell.innerHTML + "</span></span>";
	}
	catch(e) {}
}

function SetCellUnSelected()
{
	try
	{
		if (window.SelectedRowCell != null)
			window.SelectedRowCell.innerHTML = window.SelectedRowCell.children[0].children[0].innerHTML;
	}
	catch(e) {}
}

function GetSelectedRowIDs(oTable)
{
	var strRowIDs = "";
	for(var nRow = 1; nRow < oTable.rows.length; nRow++)
	{ 
		var oRow = oTable.rows[nRow];
		if (oTable.IsListAsCards)
		{
			for(var nCell = 0; nCell < oRow.cells.length; nCell++)
			{
				var oCell = oRow.cells[nCell];
				if (IsSelected(oCell) && oCell.id != "")
					strRowIDs += (strRowIDs != "" ? "," : "") + oCell.id;
			}
		}
		else
		{
			if (IsSelected(oRow) && oRow.id != "")
				strRowIDs += (strRowIDs != "" ? "," : "") + oRow.id;
		}
	}
	return strRowIDs;
}

function SelectCard(oRow, oTable, bScrollIntoView)
{
	try
	{
		var oCard = CheckRow(oRow);
		if (oCard == null)
			return;

		SetCardSelected(oCard, oTable);

		window.SelectedCard = oCard;

		if (bScrollIntoView == true) window.SelectedCard.scrollIntoView(true);
		if (bScrollIntoView == false) window.SelectedCard.scrollIntoView(false);
	}
	catch(e) {}
}

function SetCardSelected(oCard, oTable)
{
	try
	{
		SetCardUnSelected(oTable.selected_card, oTable);

		var bIsRowSelected = IsSelected(oCard);
		if (oTable != null && oTable.selected_card != null && oTable.selected_card != oCard && IsSelected(oTable.selected_card))
			oTable.selected_card.className = "clsRowSelected";
			
		oTable.selected_card = oCard;
		oCard.className = "clsRowSelectedFocus";
	}
	catch(e) {}
}

function SetCardUnSelected(oCard, oTable)
{
	try
	{
		if (!IsSelected(oCard))
			return;

		if (oTable != null && oTable.selected_card == oCard)
			oTable.selected_card = null;

		oCard.className = 'clsRowNoSelected';
		oCard.tabIndex = null;
	}
	catch(e) {}
}

//========= End select row support functions =====================================================================

top.SelectedFolder = null;

function SelectFolder(oFolder)
{
	try
	{
		if (top.SelectedFolder != null)
			top.SelectedFolder.className = 'clsFolder';
		top.SelectedFolder = oFolder;
		oFolder.className = 'clsSelectedFolder';
		oFolder.document.focus();
		oFolder.rows[1].cells[0].children[0].focus();
	} 
	catch(e) {}
}

function GetAvailableOperation1(strOperation)
{
	try
	{
		var oRow = window.SelectedRow;
		oTable = oRow.parentElement.parentElement;
		var strOperations = "," + oTable.Operations + ",";
		strOperations = strOperations.replace(/ /g, "");

		var strRowIDs = GetSelectedRowIDs(oTable)
		if (strRowIDs.split(',').length > 1)
		{
			if (strOperations.indexOf(strOperation + "_group,") != -1)
				return strOperation + "_group";
		}

		if (strOperations.indexOf(strOperation) != -1)
			return strOperation;
	}
	catch(e) {}
	
	return "";
}

function GetAvailableOperation(oTable, strOperation)
{
	try
	{
		var strOperations = "," + oTable.Operations + ",";
		strOperations = strOperations.replace(/ /g, "");

		var strRowIDs = GetSelectedRowIDs(oTable)
		if (strRowIDs != null && strRowIDs.split(',').length > 1)
		{
			if (strOperations.indexOf(strOperation + "_group,") != -1)
				return strOperation + "_group";
		}

		if (strOperations.indexOf(strOperation) != -1)
			return strOperation;
	}
	catch(e) {}
	
	return "";
}

function EditRow(oRow)
{
	try
	{
		oRow = (oRow == null ? window.event.srcElement : oRow);
		var oTable = CheckTable(oRow);
		if (oTable.IsListAsCards)
			return EditCard(oRow, oTable);

		oRow = CheckRow(oRow);
		if (oRow.rowIndex != 0)
		{
			oTable = oRow.parentElement.parentElement;
			if (GetAvailableOperation(oTable, "select") == "select") 
			{
				SelectRowID(oRow);
				return;
			}

			var strEditView = oTableHeader.EditView;
			strEditView = (strEditView == null || strEditView == "" ? "Table" : strEditView);
			var strRowAddress = RowAddress(oRow);
			strRowAddress += (strRowAddress.indexOf(':') == -1 ? ":" + strEditView : "");

			if ((strRowAddress.indexOf(":NEW") == -1 && GetAvailableOperation(oTable, "open") == "") || 
				(strRowAddress.indexOf(":NEW") != -1 && GetAvailableOperation(oTable, "new") == ""))
				return;

			var strURL = MakeURL("/site.asmx/Dialog?address=" + strRowAddress);
			strURL = SetURLParam(strURL, "is_readonly", GetParamByUrl(document.location.href, "is_readonly"));
			if (IsPressAlt())
				try	{ top.frRight.document.location.href = strURL; } catch(e) {}
			else
			if (IsPressCtrl())
				window.open(strURL, '', 'channelmode=0,toolbar=0,location=0,fullscreen=0,scrollbars=1,resizable=1,titlebar=1;top=1;left=1;', 0);
			else
			{
				SetClassForRecordRows(oTable.selected_row, 'clsRowSelectedNoFocus', 'clsRowSelectedNoFocusLine2');
				top.LastEnterFieldPos = 0;
				var oResult = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
				SetClassForRecordRows(oTable.selected_row, 'clsRowSelectedFocus', 'clsRowSelectedFocusLine2');
				AnalyzeDialogResult(oResult, oRow.document);

				window.SelectedRow.focus();	
			}
		}
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	} 
	catch(e) {}

	return false;
}

function EditCard(oRow, oTable)
{
	try
	{
		var oCard = CheckRow(oRow);
		if (oCard != null)
		{
			var strEditView = oTableHeader.EditView;
			strEditView = (strEditView == null || strEditView == "" ? "Table" : strEditView);

			var strCardAddress = RowAddress(oCard);
			strCardAddress += (strCardAddress.indexOf(':') == -1 ? ":" + strEditView : "");

			if ((strCardAddress.indexOf(":NEW") == -1 && GetAvailableOperation(oTable, "open") == "") || 
				(strCardAddress.indexOf(":NEW") != -1 && GetAvailableOperation(oTable, "new") == ""))
				return;

			var strURL = MakeURL("/site.asmx/Dialog?address=" + strCardAddress);
			strURL = SetURLParam(strURL, "is_readonly", GetParamByUrl(document.location.href, "is_readonly"));

			if (IsPressAlt())
				try	{ top.frRight.document.location.href = strURL; } catch(e) {}
			else
			if (IsPressCtrl())
				window.open(strURL, '', 'channelmode=0,toolbar=0,location=0,fullscreen=0,scrollbars=1,resizable=1,titlebar=1;top=1;left=1;', 0);
			else
			{
				oTable.selected_card.className = 'clsRowSelectedNoFocus';
				top.LastEnterFieldPos = 0;
				var oResult = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
				oTable.selected_card.className = 'clsRowSelectedFocus';
				AnalyzeDialogResult(oResult, oCard.document);
			}
		}
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	} 
	catch(e) {}

	return false;
}

function AnalyzeDialogResult(oResult, oDoc)
{
	try
	{
		if (oResult == null)
			return;

		if (IsDialog())
		{
			if (oResult.indexOf("Close=\"Parent\"") != -1)
			{
				window.close();
				return;
			}
			oDoc = (oResult.indexOf("Refresh=\"Parent\"") != -1 ? top.frames.DialogMainFarame.document : oDoc);
			var strURL = oDoc.location.href;
			if (window.SelectedRow != null)
				strURL = SetURLParam(strURL, "selected_row_index", window.SelectedRow.rowIndex);
			oDoc.location.href = strURL;
		}
		else
		{
			oDoc = (oResult.indexOf("Refresh=\"Parent\"") != -1 ? top.frRight.document : oDoc);
			oDoc.location.href = SetURLParam(oDoc.location.href, "selected_row_index", (window.SelectedRow != null ? window.SelectedRow.rowIndex : ""));
		}
	}
	catch(e) {}
}

function DeleteRow(oRow, oMenuElement)
{
	return ExecConfirmOperation(oRow, "delete", "Вы действительно хотите выполнить удаление", oMenuElement);
}

function CopyRow(oRow, oMenuElement)
{
	return ExecConfirmOperation(oRow, "copy", "Вы действительно хотите создать копию", oMenuElement);
}

function ExecConfirmOperation(oRow, strOperation, strQuery, oMenuElement)
{
	try
	{
		oRow = CheckRow(oRow);
		var oTable = CheckTable(oRow);

		var strSelectedIDs = GetSelectedRowIDs(oTable);
		var strOperation = GetAvailableOperation(oTable, strOperation);
		var strAddress = RowAddress(oRow);
		var nRecordCount = strSelectedIDs.split(',').length;

		if (strOperation == "")
			return;

		if (nRecordCount > 1)
		{
			if (!IsSelected(oRow) || !IsGroupOperation(strOperation))
			{
				SelectRow(oRow);
				nRecordCount = 1;
			}
			if (IsGroupOperation(strOperation))
				strAddress = oTable.DataAddress + "-" + strSelectedIDs;
		}

		if (strAddress.indexOf(':NEW') != -1 ||
			strQuery.length > 0 && !confirm(strQuery + " " + (nRecordCount > 1 ? nRecordCount + " записей" : "записи") + '?'))
				return;

		var strURL = MakeURL("/gate.asmx/WebExecute?address=" + strAddress);
		strURL = SetURLParam(strURL, "address_operation", strOperation);
		strURL = SetURLParam(strURL, "after_operation_action", oMenuElement != null && oMenuElement.AfterOperationAction != null && oMenuElement.AfterOperationAction.length > 0? oMenuElement.AfterOperationAction : "refresh");
		strURL = SetURLParam(strURL, "is_operation_from_list", "true");
		if (IsDialog())
			strURL = SetURLParam(strURL, "is_dialog", "true");
		window.document.frames.Execute.document.location.href = strURL;
	}
	catch(e) {}
}

function RowAddress(oRow)
{
	try
	{
		oRow = (oRow != null ? oRow : window.SelectedRow);
		oRow = (oRow != null ? oRow : window.SelectedCard);

		if (oRow != null && oRow.RowAddress != null)
			return oRow.RowAddress;

		oTable = CheckTable(oRow);
		return oTable.DataAddress + '-' + oRow.id;
	}
	catch(e) {}
}

function TableKeyUp(nKeyCode, oMenuElement)
{
	try
	{
		var oRow = (window.SelectedRow != null ? window.SelectedRow : window.SelectedCard);
		var oTable = CheckTable(oRow);
		nKeyCode = (nKeyCode == null ? window.event.keyCode : nKeyCode);
		switch(nKeyCode)
		{
			case 9:		return true;
			case 13:	EditRow(oRow); break; 
			//	left
			case 37:    GoToPreviousCell();
				break;
			//	up
			case 38:	GoToPreviousRecord();
				break;
			//	right
			case 39:	GoToNextCell();
				break;
			//	down
			case 40:	GoToNextRecord();
				break;
			//	page down, end
			case 34:
			case 35:	GoToLastRecord();
				break;
			//	page up, home
			case 33:	
			case 36:	GoToFirstRecord();
				break;
			//	insert
			case 45:	EditRow(window.SelectedRow.parentElement.lastChild); break;
			//	delete
			case 46:	DeleteRow(oRow, oMenuElement); break;
			case 27:	return;
			default: 	
			{
				if (IsPressCtrl() || IsPressShift() || IsPressAlt())
					return;

				var strChar = String.fromCharCode(window.event.keyCode).toUpperCase();
				var isSymbol = (strChar >= '0' && strChar <= '9') ||
								(strChar >= 'A' && strChar <= 'Z') ||
								(strChar >= '_' && strChar <= '_');
				if (window.SelectedRowCell != null && isSymbol)
				{
					var oTD = GetHeaderCell(window.SelectedRowCell);
					GetFilter(oTD, true);
					return;
				}
			}
		}

		window.event.cancelBubble = true;
		window.event.returnValue = false;
		return false;
	}
	catch(e) {}
}

top.SelectedFolder = null;

function ViewLoad()
{
	try
	{
		top.SelectedFolder = this.document.body.firstChild.firstChild.firstChild;
		top.SelectedFolder.focus();
	}
	catch(e) {}
}

function ViewKeyUp()
{
	try
	{
		switch(window.event.keyCode)
		{
			case 9:		return true;
			case 13:	top.SelectedFolder.ondblclick(); break; 
			case 37:
			case 38:	if (top.SelectedFolder.previousSibling != null) top.SelectedFolder.previousSibling.focus(); else top.SelectedFolder.parentElement.lastChild.focus(); break;
			case 39:
			case 40:	if (top.SelectedFolder.nextSibling != null) top.SelectedFolder.nextSibling.focus(); else top.SelectedFolder.parentElement.firstChild.focus(); break;
			case 34:	
			case 35:	top.SelectedFolder.parentElement.lastChild.focus(); break;
			case 33:	
			case 36:	top.SelectedFolder.parentElement.firstChild.focus(); break;
		}
		window.event.cancelBubble = true;
		window.event.returnValue = false;
		return false;
	}
	catch(e) {}
}

function SelectRowID(oRow)
{
	try
	{
		if (oRow.IsExpand && !IsPressCtrl())
		{
			var strRowAddress = RowAddress(oRow);
			var strURL = SetURLParam(document.location.href, "address", strRowAddress);
			strURL = SetURLParam(strURL, "data_root_dir", "");
			strURL = SetURLParam(strURL, "address_first", "");
			document.location.href = strURL;
			return;
		}
		
		var strFindColumn = GetParamByUrl(document.location.href, "show_field")
		strFindColumn = (strFindColumn != "" ? strFindColumn : oTableHeader.NameField);

		var nCellPos = 0;
		for (var nRow = 0; nRow < (IsListStacked()? oTableHeader.rows.length : 1); nRow++)
		{
			var RowCells = oTableHeader.rows[nRow].cells;
			var nCell;
			for (nCell = 0; nCell < RowCells.length; nCell++)
			{
				if (RowCells[nCell].FieldName == strFindColumn ||
					RowCells[nCell].FieldID == strFindColumn)
				{
				    nCellPos = nCell;
					break;
				}
			}
			if (nCell < RowCells.length)
				break;
		}

		window.returnValue = oRow.id + ":" + (nCellPos != -1 && nCellPos < oRow.cells.length ? oRow.cells[nCellPos].innerText : oRow.id);
		window.close();
	}
	catch(e) {}
}

function SelectImage(ob)
{
	try
	{
		window.returnValue = ob.RowID + ":" + ob.innerText.replace(/\r/g, "").replace(/\n/g, "");
		window.close();
	}
	catch(e) {}
}

top.nFindTimerHandle = null;

function SelectRowByData(nCol, strData, bIsExecute)
{
	return false;

	try
	{
		if (top.nFindTimerHandle != null && top.nFindTimerHandle != "")
			clearTimeout(top.nFindTimerHandle);

		if (bIsExecute != true)
			top.nFindTimerHandle = setTimeout("SelectRowByData('" + nCol + "', '" + strData + "', true)", 1000);
		else
		{
			strData = strData.toUpperCase();
			for (var nRow = 0; nRow < oTableData.rows.length; nRow++)
			{
				if (oTableData.rows[nRow].cells[nCol].innerText.toUpperCase().indexOf(strData) != -1)
				{
					SelectRow(oTableData.rows[nRow], true);
					return;
				}
			}
			top.nFindTimerHandle = null;
		}
	}
	catch(e) {}
}

function FindElement(ob, strName)
{
	while (ob != null)
	{
		if (ob.all(strName) != null)
			return ob.all(strName);
		ob = ob.parentElement;
	}
	return null;
}

function FindElementByTagName(ob, strParentTagName)
{
	var strParentTagNameUpperCase = strParentTagName.toUpperCase();

	while (ob != null)
	{
		if (ob.tagName.toUpperCase() == strParentTagNameUpperCase)
			return ob;
		ob = ob.parentElement;
	}
	return null;
}

function GetFromDictionary(oButton)
{
	try
	{
		var oInput = FindElement(window.event.srcElement, 'sfd');
		var oText = FindElement(window.event.srcElement, 'sfd_text');
		if (oInput == null && oText == null)
			return;

		var strFullAddress = oButton.Address;
		//	Разделяем адрес на сам адрес и view 
		var aFullAddress = strFullAddress.split('&');

		var strAddress = aFullAddress[0];
		var aAddress = strAddress.split(':');
		//	Делим адрес на уровни
		var aLevels = aAddress[0].split('/');
		//	Разделяем последний уровень на имя объекта и ID
		var aLastLevel = aLevels[aLevels.length - 1].split('-');
		//	Если есть ID на последнем уровне то исключаем его
		if (aLastLevel.length > 1)
		{
			strAddress = aAddress[0].substring(0, aAddress[0].length - aLastLevel[1].length) + (aAddress.length > 1 ? ':' + aAddress[1] : '');
			strFullAddress = strFullAddress.replace(aFullAddress[0], strAddress);
		}
		strFullAddress = "/site.asmx/Dialog?" + strFullAddress + "&address_max=50&is_select_only=true";
		var strURL = MakeURL(strFullAddress);
		strURL = AppendDependenceFieldsValue(strURL, oButton.form);

		var strDialogWidth = GetParamByUrl(strURL, "window_width");
		strDialogWidth = (strDialogWidth != "" ? strDialogWidth : "600");
		var strDialogHeight = GetParamByUrl(strURL, "window_height");
		strDialogHeight = (strDialogHeight != "" ? strDialogHeight : "500");

		var oResult = window.showModalDialog(strURL, top, "dialogWidth: " + strDialogWidth + "px; dialogHeight: " + strDialogHeight + "px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
		if (oResult != null)
			SetValueToInput(oInput, oText, oResult);
	}
	catch(e) {}
}

function AppendDependenceFieldsValue(strURL, oForm)
{
	try
	{
		//	Проверяем записит ли данная ссылка от параметров формы - параметр dependence_fields
		var strDependenceFields = GetParamByUrl(strURL, "dependence_fields"); 
		if (strDependenceFields != "" && oForm != null)
		{
			var aDependenceFields = strDependenceFields.split(';');
			for(var nDependenceField = 0; nDependenceField < aDependenceFields.length; nDependenceField++)
			{
				var strFieldName = "_" + aDependenceFields[nDependenceField];
				if (oForm.elements[strFieldName] != null)
					strURL = SetURLParam(strURL, strFieldName, oForm.elements[strFieldName].value);
				else
					strURL = SetURLParam(strURL, strFieldName, "");
			}
		}
	}
	catch(e) {}

	return strURL;
}


var oEditDictionaryInput = null;
var oEditDictionaryText = null;

function EditDictionary(strType, bIsRefreshAll)
{
	try
	{
		var oSelect = FindElement(window.event.srcElement, 'sfd');
		if (strType.toUpperCase() != "NEW" && (oSelect == null || oSelect.value == "" || parseInt(oSelect.value) < 0))
		{
			alert("Не выбран элемент для редактирования!");
			var oText = FindElement(window.event.srcElement, 'sfd_text');
			if (oText != null)
				oText.focus();
			return;
		}
		var strAddress = (oSelect.DictAddress != null ? oSelect.DictAddress : window.event.srcElement.parentElement.children[0].Address.substring(8));
		var strDictAddress = oSelect.DictAddress;
		if (strDictAddress == null)
		{
			var oText = FindElement(window.event.srcElement, 'sfd_text');
			if (oText != null)
			{
				strDictAddress = oText.DictAddress;
				strDictAddress = GetParamByUrl("?" + strDictAddress, "address");
			}
		}
		strAddress = strAddress.split('&')[0];
		var aLevels = strAddress.split('/');
		var strLastLevel = aLevels[aLevels.length - 1].split(':')[0].split('-')[0];
		strAddress = strAddress.replace(aLevels[aLevels.length - 1], strLastLevel);
		strAddress = "/site.asmx/Dialog?address=" + strAddress + (strType.toUpperCase() != "NEW" ? "-" + oSelect.value : "") + ":" + strType + "&dictionary_address=" + (strDictAddress != null ? strDictAddress : "");
		var strURL = MakeURL(strAddress);
		top.LastEnterFieldPos = 0;
		var oResult = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
		if (oResult != null)
		{
			try
			{
				oEditDictionaryInput = oSelect;
				oEditDictionaryText = FindElement(window.event.srcElement, 'sfd_text');
				SetValueToInput(oEditDictionaryInput, oEditDictionaryText, ":", true);
			
				var strID = GetValueFromResult(oResult, "_id");
				if (strID != null)
				{
					var strShowField = (oEditDictionaryText.show_field == null ? "name" : oEditDictionaryText.show_field);
					strURL = strURL.replace("/site.asmx/Dialog", "/gate.asmx/WebExecute");
					strURL = strURL.replace(":New", "-" + strID);
					strURL += "&address_fields=%3C%23FULL_DATA_NAME%23%3E._id%2B':'%2B%3C%23FULL_DATA_NAME%23%3E." + strShowField + ",%3C%23FULL_DATA_NAME%23%3E._id&out_driver=VALUE";
					strURL = strURL.replace(/%3C%23FULL_DATA_NAME%23%3E._id/g, "convert(varchar(64),%3C%23FULL_DATA_NAME%23%3E._id)");
					Download.startDownload(strURL, onDownloadRowDone);
				}
			}
			catch(e) {}
		}
		window.parent.focus();	
	}
	catch(e) {}
}

function onDownloadRowDone(strText)
{
	try
	{
		SetValueToInput(oEditDictionaryInput, oEditDictionaryText, strText);
		oEditDictionaryInput = null;
		oEditDictionaryText = null;
	}   	
	catch(e) {}
}

function SetValueToInput(oInput, oText, oResult, bIsPassChange)
{
	try
	{
		var aResult = oResult.split(':');
		if (aResult.length > 1)
		{
			if (oText != null && oText.length == null)
			{
				//	Фиксируем ширину контрола перед установкой значения
				var oRect = oText.getBoundingClientRect();
				oText.runtimeStyle.width = (oRect.right - oRect.left) + "px";

				oText.innerText = oResult.substr(aResult[0].length + 1);
				oText.focus();
			}
	
			if (oInput == null)
				return;

			oInput.old_value = oInput.value;
			oInput.value = (oInput.hidden == false && oText == null ? oInput.value : "") + aResult[0];
			SetValueToMultyEntryField(oInput);

			if (oText != null)
			{
				oText.runtimeStyle.fontWeight = (oInput.value != "" ? "bold" : "normal");
				oText.runtimeStyle.color = (oInput.value != "" ? "" : "white");
				oText.runtimeStyle.backgroundColor = (oInput.value != "" ? "" : "red");
				//	Запоминаем а какое стало у нас текстовое представление выбранного значения
				try { oText.old_value = oText.value; } catch(e) {}
			}

			if (oInput.old_value == oInput.value || bIsPassChange)
				return;

			oInput.old_value = oInput.value;
			if (oInput.IsRefreshOnChange == "true")
				RefreshOnChange(oInput);

	   		if (oInput.ExecuteOnChangeOparation != null && oInput.ExecuteOnChangeOparation != "")
			{
				oInput.is_changed = "true";
				ExecuteOnChange(oInput, oInput.ExecuteOnChangeOparation, oInput.ExecuteOnChangeView);
			}
		}
	}
	catch(e) {}
}

function RefreshOnChange(oElement)
{
	try
	{
		top.bNoUnlockRecord = true;

		oElement = (oElement == null ? window.event.srcElement : oElement);
		var oForm = oElement.form;

		if (oForm == null)
		{   	
			oForm = window.event.srcElement;
			while (oForm != null && oForm.tagName.toUpperCase() != "FORM")
				oForm = oForm.parentElement;
		}

		if (oForm != null)
		{
			var oInput = window.document.createElement("<Input type=hidden name=init_refresh_field>");
			oInput.value = oElement.name.substring(1);
			oForm.appendChild(oInput);

			oForm.is_changed = 'false';
			oForm.target = "_self";
			var strOriginalAddressOperation = GetParamByUrl(document.location.href, "address_operation");
			oForm.elements["address_operation"].value = (strOriginalAddressOperation != "" ? strOriginalAddressOperation : "get");
			oForm.submit();
			top.bIsDialogResized = false;
	
			DisabledForm(oForm, true);
		}

	}
	catch(e) {}
}

function ExecuteOnChange(oElement, strOperation, strView)
{
	try
	{
		if (oElement == null || oElement.is_changed != 'true' || oElement.form == null)
			return;
		oElement.is_changed = "";
		var oForm = oElement.form;

		//	Устанавливаем флаг что идет команда по изменению поля
		IsExecuteOnChangeOnProcess = true;

		//	Устанавливаем что результат мы хотим получить в виде сообщения
		var oldOutDriver = oForm.elements["out_driver"].value;
		var strOldAddress = oForm.elements["address"].value;
		var strOldOperation = oForm.elements["address_operation"].value;


		oForm.elements["out_driver"].value = "MESSAGE";
		oForm.elements["address_operation"].value = strOperation;
		if (strView == null)
			oForm.elements["address"].value = strOldAddress.split(':')[0] + ":" + strView;

		var strElementName = (oElement.preset != 'percent' ? oElement.name.substring(1) : oElement.FieldName);
		//	Добавляем в форму параметр в котром заданно, кто вызвал выполнение команды
		var oInitRefreshField = window.document.createElement("<input type=hidden name=init_refresh_field value='" + strElementName + "'>");
		oForm.appendChild(oInitRefreshField);

		//	Добавляем в форму первым пустой параметр, который может быть затерт IE
		if (oForm.elements[0] != null && oForm.elements[0].name != "nop")
		{
			var oInput = window.document.createElement("<input type=hidden name=nop value=nop>");
			oForm.insertBefore(oInput, oForm.firstChild);
		}

		//	Посылаем команду на сервер
		oForm.submit();
		
		//	Удаляем параметр в котром заданно, кто вызвал выполнение команды
		oForm.removeChild(oInitRefreshField);

		DisabledForm(oForm, true, true);

		//	Востанавливаем исходнык значения параметров
		oForm.elements["out_driver"].value = oldOutDriver;
		oForm.elements["address"].value = strOldAddress;
		oForm.elements["address_operation"].value = strOldOperation;
	}
	catch(e) {}
}

function DeleteImage(ob, strFieldName)
{
	try
	{
		var oTable = ob;
		while (oTable != null && oTable.tagName.toUpperCase() != "TABLE")
			oTable = oTable.parentElement;
		if (oTable == null)
			return;

		var oDiv = null;
		var oInput = null;
		var oImg = null;
		for(var nPos = 0; nPos < oTable.all.length; nPos++)
		{
			if (oDiv == null && oTable.all[nPos].tagName.toUpperCase() == "DIV")
				oDiv = oTable.all[nPos];
			if (oInput == null && oTable.all[nPos].name == "delete_file_" + strFieldName)
				oInput = oTable.all[nPos];
			if (oImg == null && oTable.all[nPos].tagName.toUpperCase() == "IMG")
				oImg = oTable.all[nPos];
		}

		if (oDiv != null)
			oDiv.innerText = "";
		if (oInput != null)
			oInput.value = "True";
		if (oImg != null)
			oImg.src = "/editor/images/empty_img.gif";

		ob.parentElement.children[1].disabled = true;
		ob.parentElement.children[2].disabled = true;
	}
	catch(e) {}
}

// ========================= Select event functions ================================================================

function OnSelectChange(oSelect)
{
	try
	{
		if (oSelect.IsRefreshOnChange)
			RefreshOnChange();

		if (oSelect.ExecuteOnChangeOparation != null)
			ExecuteOnChange(oSelect, oSelect.ExecuteOnChangeOparation, oSelect.ExecuteOnChangeView);
	}
	catch(e) {}
}

var oSelectElement = null;

function SelectKeyPress(oSelect)
{
	if (window.event.keyCode >= 32)
		oSelect.filter = Trim((oSelect.filter != null ? oSelect.filter : '') + String.fromCharCode(window.event.keyCode).toUpperCase());
	if (oSelect.filter == null || oSelect.filter == "")
		return;
	for(var nPos = 0; nPos < oSelect.options.length; nPos++)
	{
		if (Trim(oSelect.options[nPos].innerText.toUpperCase()).indexOf(oSelect.filter) == 0)
		{
			oSelect.selected_value = oSelect.options[nPos].value;
			oSelect.options[nPos].selected = true;
			break;
		}
	}
	if (oSelect.timeout_handle != null && oSelect.timeout_handle != "")
		clearTimeout(oSelect.timeout_handle);
	oSelect.timeout_handle = setTimeout("SelectKeyPressTimeout('" + oSelect.name + "')", 1500);
	oSelectElement = oSelect;

	window.event.cancelBubble = true;
	window.event.returnValue = false;
	return false;
}

function SelectKeyPressTimeout(strSelectName)
{
	try
	{
		var oSelect = document.forms[0][strSelectName];
		oSelect = (oSelect.length == null ? oSelect : oSelectElement);
		oSelect.focus();
		oSelect.value = oSelect.selected_value;
		oSelect.filter = "";
		oSelect.timeout_handle = "";
		oSelect.fireEvent("onchange");
	}
	catch(e) {}
}

var oSelectLong = null;

function SelectLongKeyPress(oInput)
{
	if (oInput.value == oInput.old_value)
		return;
	oInput.old_value = oInput.value;
	IsExecuteOnChangeOnProcess = false;
	closePopup();

	if (oInput.timeout_handle != null && oInput.timeout_handle != "")
		clearTimeout(oInput.timeout_handle);
	if (oInput.value != "")
		oInput.timeout_handle = setTimeout("SelectLongKeyPressTimeout()", 1500);
	oInput.onblur = SelectLongKeyPressOnBlur;
	oInput.onkeydown = SelectLongKeyDown;
	oInput.runtimeStyle.fontWeight = "normal";
	oInput.runtimeStyle.color = "";
	oInput.runtimeStyle.backgroundColor = "";

	oSelectLong = oInput;
	var oHiddenInput = FindElement(oInput, 'sfd');
	if (oHiddenInput.old_value == null)
		oHiddenInput.old_value = oHiddenInput.value;
	oHiddenInput.value = "";

	return true;
}

function SelectLongKeyDown()
{
	try
	{
		var oInput = oSelectLong;
		if (window.event.keyCode == 40 && oInput.value != "")
			SelectLongKeyPressOnBlur();
	}   	
		
	catch(e) {}
}

function SelectLongKeyPressOnBlur()
{
	try
	{
		var oInput = oSelectLong;
		if (oInput != null && oInput.timeout_handle != null && oInput.timeout_handle != "" && oInput.value != "")
		{
			IsExecuteOnChangeOnProcess = true;
			clearTimeout(oInput.timeout_handle);
			oInput.timeout_handle = setTimeout("SelectLongKeyPressTimeout()", 10);
		}
		else
		{
			var oInput = window.event.srcElement;
			SetIDForSelectLong(oInput, oInput.value, "");
		}
	}   	
	catch(e) {}
}

function SelectLongKeyPressTimeout()
{
	try
	{
		var oInput = oSelectLong;
		if (oInput.timeout_handle != null && oInput.timeout_handle != "")
		{
			clearTimeout(oInput.timeout_handle);
			oInput.timeout_handle = null;
		}

		var oRect = oSelectLong.parentElement.getBoundingClientRect();
		var strURL = "/gate.asmx/WebExecute?" + oInput.DictAddress + (oInput.show_field != null ? "&show_field=" + oInput.show_field : "") + "&filter_" + oInput.show_field + "=" + (oInput.value != null ? oInput.value.replace(/\+/gi, "%2B") : "") + (oInput.AdditionalParams != null ? oInput.AdditionalParams : "") + "&__query_for_vi=true&out_driver=DROP_LIST&address_fields=%23.*&address_max=26&width=" + (oRect.right - oRect.left);
		strURL = MakeURL(strURL);
		strURL = RemoveURLParamStartsWith(strURL, "_CURRENT_AUTO_ID");
		strURL = AppendDependenceFieldsValue(strURL, oInput.form);
		Download.startDownload(strURL, onDownloadSelectLongDone);
		oInput.filter = "";
		IsExecuteOnChangeOnProcess = true;
	}   	
	catch(e) {}
}

function onDownloadSelectLongDone(strText)
{
	var oInput = oSelectLong;
	oSelectLong = null;
	try
	{
		if (strText.indexOf("#VALUE#") == 0)
		{
			//	Это единичное значение и сразу помещаем его в поле
			var aValue = strText.substring(7).split('|');
			var strShowText = (aValue.length > 1 ? strText.substring(7 + aValue[0].length + 1) : "");
			SetIDForSelectLong(oInput, strShowText, aValue[0]);
		}
		else
		{
			//	Если это не единичное значение, то формируем пользователю список на выбор значения
			var oRect = oInput.getBoundingClientRect();
			top.oPopupEventSrc = oInput;
			top.oPopupOpenerWindow = window;
			top.oPopup.xPos = oRect.left + (top != null ? window.screenLeft - top.screenLeft : 0);
			top.oPopup.yPos = oRect.bottom + (top != null ? window.screenTop - top.screenTop : 0);
			onDownloadMenuDone(strText);
			oInput.focus();
			oInput.onkeydown = KeyUpForDropDown;
			KeyUpForDropDown(36);
		}

		IsExecuteOnChangeOnProcess = false;
	}   	
	catch(e) {}
}

function SelectFromDropDown(oTR)
{
	try
	{
		var oInput = top.oPopupEventSrc;
		var oShowField = oInput.show_field;

		var oTable = oTR.document.all["oTableHeader"];
		var nCellPos = 0;
		if (oTable != null)
		{
			for (var nRow = 0; nRow < (IsListStacked() ? oTable.rows.length : 1); nRow++)
			{
				var RowCells = oTable.rows[nRow].cells;
				var nCell;
				for (nCell = 0; nCell < RowCells.length; nCell++)
				{
					if (RowCells[nCell].FieldName == oShowField ||
						RowCells[nCell].FieldID == oShowField)
					{
					    nCellPos = nCell;
						break;
					}
				}
				if (nCell < RowCells.length)
					break;
			}
		}

		SetIDForSelectLong(oInput, oTR.cells[nCellPos].innerText, oTR.RowID);
		closePopup();
	}   	
	catch(e) {alert(e)}
}

function ChangeIDForSelectLong(oHiddenInput)
{
	try
	{
		var oInput = FindElement(oHiddenInput, 'sfd_text');
		if (oHiddenInput.value == "")
		{
			oInput.value = "";
			SetIDForSelectLong(oInput, "", "");
			return;
		}

		oSelectLong = oInput;

		var strURL = "/gate.asmx/WebExecute?" + oInput.DictAddress.split('&')[0] + '-' + oHiddenInput.value + (oInput.show_field != null ? "&show_field=" + oInput.show_field : "") + "&__query_for_vi=true&out_driver=DROP_LIST";
		Download.startDownload(MakeURL(strURL), onDownloadSelectLongDone);
	}   	
	catch(e) {}
}

function SetIDForSelectLong(oInput, strValue, strID)
{
	try
	{
		if (strValue == "" && strID == "")
			strValue = oInput.value;

		//	Если устанавливаем какое-то значение, то отслеживать уход из контрола нам уже не нужно
		oInput.onblur = null;

		oInput.value = strValue;
		oInput.old_value = strValue;
		var oHiddenInput = FindElement(oInput, 'sfd');
		oHiddenInput.value = strID;

		SetValueToMultyEntryField(oHiddenInput);

		var bIsNoError = (oHiddenInput.value != "" || oInput.value == "");

		oInput.runtimeStyle.fontWeight = (bIsNoError ? "bold" : "normal");
		oInput.runtimeStyle.color = (bIsNoError ? "" : "white");
		oInput.runtimeStyle.backgroundColor = (bIsNoError ? "" : "red");

		if (oHiddenInput.value != oHiddenInput.old_value)
		{
			if (oHiddenInput.IsRefreshOnChange == "true")
				RefreshOnChange(oHiddenInput);
			else
	   		if (oHiddenInput.ExecuteOnChangeOparation != null && oHiddenInput.ExecuteOnChangeOparation != "")
			{
				oHiddenInput.is_changed = "true";
				ExecuteOnChange(oHiddenInput, oHiddenInput.ExecuteOnChangeOparation, oHiddenInput.ExecuteOnChangeView);
			}
		}
	}   	
	catch(e) {}
}

function DropDownMouseOver(oTR)
{
	try
	{
		var oTable = oTR.document.body.all('oTable');
		if (oTable.SelectedRow == oTR)
			return;

		if (oTable.SelectedRow != null)
		{
			var oSelected = oTable.SelectedRow;
			oSelected.runtimeStyle.backgroundColor = oSelected.style.backgroundColor;
			oSelected.runtimeStyle.color = oSelected.style.color;
		}

		oTable.SelectedRow = oTR;
		oTR.runtimeStyle.backgroundColor = "highlight";
		oTR.runtimeStyle.color = "highlighttext";
		oTR.IsSelected = true;
	}
	catch(e) {}
} 

function KeyUpForDropDown(keyCode)
{
	try
	{
		keyCode = (keyCode != null ? keyCode : window.event.keyCode);
		if ((keyCode < 33 || keyCode > 40) && keyCode != 13)
			return;

		//	Ищем выделенную строку
		var oTable = top.oPopup.window.document.body.all('oTable');
		var SelectedRow = oTable.SelectedRow;

		//	Если нашли выбранную строку и нажата клавиша ENTER
		if (keyCode == 13 && SelectedRow != null)
		{
			SelectedRow.fireEvent("onclick");
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return false;
		}

		//	Определяем новую выделенную строку
		var nNewSelect = (SelectedRow != null ? SelectedRow.rowIndex : 0);
		var strScrollType = false;
		switch (keyCode)
		{
			case 33: nNewSelect -= 10; break;
			case 34: nNewSelect += 10; break;
			case 36: nNewSelect = 1; break;
			case 35: nNewSelect = oTable.rows.length - 1; break;
			case 38: nNewSelect--; strScrollType=true; break;
			case 40: nNewSelect++; break;
		}

		//	Проверяем что новая выделенная строка попадает в наш диапазон
		if (nNewSelect < 1) nNewSelect = 1;
		if (nNewSelect > oTable.rows.length - 1) nNewSelect = oTable.rows.length - 1;
		oTable.rows[nNewSelect].fireEvent("onmouseover");
		oTable.rows[nNewSelect].scrollIntoView(strScrollType);

		window.event.cancelBubble = true;
		window.event.returnValue = false;
		return false;
	}   	
	catch(e) {}
}

function ShowTableTips()
{
	try
	{
		if (window.event.srcElement == null)
			return;

		if ((window.event.srcElement.title == null || window.event.srcElement.title == "") &&

			(window.event.srcElement.tagName.toUpperCase() == "TD" || 
			window.event.srcElement.tagName.toUpperCase() == "BUTTON") &&

			window.event.srcElement.all.tags("TD").length == 0 &&
			window.event.srcElement.all.tags("SELECT").length == 0 &&
			window.event.srcElement.all.tags("A").length == 0 &&
			window.event.srcElement.all.tags("BUTTON").length == 0)
		{
			var strText = window.event.srcElement.innerText;
			strText = Trim(strText);
			if (strText.length > 0 && strText.substring(strText.length - 1) == ':')
				strText = Trim(strText.substring(0, strText.length - 1));
			window.event.srcElement.title = (strText.length > 1000 ? strText.substring(0, 1000) + '...' : strText);
		}
	}
	catch(e) {}
}

function Next()
{
	try
	{
		top.bIsSave = true;
		document.forms.ExecuteForm.submit();
	}
	catch(e) {}
}

var oLastDisableForm = null;
var oLastExecuteForm = null;
 
function ExecOperation(oButton, strOperation, strMessageText, strView, strAfterOperationAction, strAddress)
{
	try
	{
		if (strMessageText != null && strMessageText != "" && !confirm('Вы действительно хотите выполнить ' + strMessageText + '?'))
		{
			if (oLastDisableForm != null)
				DisabledForm(oLastDisableForm, false);
			return;
		}

		//	Если сказано, что перед выполнением нужно сохранить запись
		//	и это не операция по умолчанию (а такими могут быть только "add" и "update")
		//	и это не операция "update", то сохраняем предварительно данные с формы
		if (oButton != null && oButton.IsSaveRecord == "true" && strOperation != "" && strOperation != "update")
			ExecOperation(oButton, "update", "", "", "edit");

		switch (strOperation)
		{
			case "help":
			{
				var strHelpID = "";
				if (window.event != null && window.event.srcElement != null)
				{
					if (window.event.srcElement.Address != null)
						strAddress = window.event.srcElement.Address;
					if (strAddress == null || strAddress == "") 
						strAddress = window.document.body.Address;

					var oElement = window.event.srcElement;
					while (strHelpID == "" && oElement != null)
					{
						if (oElement.HelpID != null)
							strHelpID = oElement.HelpID;
						oElement = oElement.parentElement;
					}
				}
				strHelpID = (strHelpID == "" || strHelpID == "BUTTON_HELP" ? "UI_DEFAULT" : strHelpID);

				strAddress = (strAddress == null ? strAddress : "");
				if (strAddress == "")
				{
					var oForm = oButton.form;
					if (oButton != null && oButton.form != null)
						strAddress = oButton.form.elements["address"].value;
				}

				if (strAddress == "" || strAddress == null)
					strAddress = GetParamByUrl(window.document.location.href, "address"); 

				if (strAddress == "" || strAddress == null)
					strAddress = "system.hi";

				var strURL = MakeURL("/gate.asmx/WebExecute?address=" + strAddress.split(':')[0] + ":Help" + (strHelpID != "" ? "-" + strHelpID : ""));
				window.showHelp(strURL);
				break;
			}
			case "close":	
			{
				DisabledForm((oButton != null ? oButton.form : null), true); 
				DialogClose(true); 
				break;
			}
			default:
			{
				var oForm = oButton.form;
				oForm.OldAddress = oForm.elements["address"].value;
				oForm.OldOperation = oForm.elements["address_operation"].value;
				try 
				{ 
					oForm.OldIsReadOnly = oForm.elements["is_readonly"].value; 
					oForm.elements["is_readonly"].value = false;
				} 
				catch(e) {}
				if (strAfterOperationAction != null)
					try { oForm.elements["after_operation_action"].value = strAfterOperationAction; } catch(e) {}


				//	Если выполнение запроса происходит под отладчиком и нет елемента context_debug_mode
				//	создаем его и устанавливаем в true 
				if (GetDebugMode())
				{
					if (oForm.elements("context_debug_mode") == null)
					{
						var oInput = window.document.createElement("<input type=hidden name=context_debug_mode value=true>");
						oForm.insertBefore(oInput, oForm.firstChild);
					}
					SetDebugMode(false);
				}

				if (strOperation != null && strOperation != "")
				{
					if (strOperation == "get_dialog" || strOperation == "get_window" || strOperation == "get_for_print")
						oForm.elements["address_operation"].value = "";
					else
						oForm.elements["address_operation"].value = strOperation;
				}

				if (strView != null && strView != "")
				{
					if (strAddress == null || strAddress == "")
						oForm.elements["address"].value = oForm.OldAddress.split(':')[0] + ":" + strView;
					else
						oForm.elements["address"].value = strAddress + ":" + strView;
				}

				if (strOperation.indexOf("_process") != -1 || strOperation.indexOf("_dialog") != -1 ||
					strOperation.indexOf("_window") != -1 || strOperation.indexOf("_print") != -1)
				{
					var strParams = "message=" + strMessageText;
					for(var nElement = 0; nElement < oForm.elements.length; nElement++)
					{
						var oElement = oForm.elements[nElement];
						if (oElement.value.length > 64 && oElement.name.indexOf("address") == -1)
							continue;
						if (oElement.name == null || oElement.name == "" || oElement.value == "" || oElement.tagName.toUpperCase() == "BUTTON")
							continue;
						strParams += "&" + oElement.name + "=" + oElement.value;
					}
			
					if (strOperation.indexOf("_process") != -1)
					{
	    				var strURL = MakeURL("/site.asmx/AlertDialog?" + strParams);
						var oResult = window.showModalDialog(strURL, top, "dialogWidth: 300px; dialogHeight: 50px; edge: Raised; center: Yes; help: No; resizable: No; status: No; scroll: no");
						if (document.all['data_frame'] != null)
						{
							if (oResult != null && oResult.indexOf('Main') != -1)
								oForm.document.location.href = oForm.document.location.href;
							else
								document.all['data_frame'].src = document.all['data_frame'].src;
						}
					}
					if (strOperation.indexOf("_dialog") != -1 || strOperation.indexOf("_window") != -1 ||
						strOperation.indexOf("_print") != -1)
					{
	    				var strURL = MakeURL("/site.asmx/Dialog?" + strParams);
						strURL = SetURLParam(strURL, "out_driver", "");
						strURL = SetURLParam(strURL, "editor_id", "");
						if (strOperation.indexOf("_dialog") != -1)
						{
							top.LastEnterFieldPos = 0;
							var oResult = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
							AnalyzeDialogResult(oResult, oForm.document);
							window.parent.focus();	
						}
						else
						{
							var strTarget = (oForm.elements["_target"] != null ? oForm.elements["_target"].value : "_blank");
							var nLeft = screen.width * 0.1;
							var nTop = screen.height * 0.1;
							var nWidth = screen.width * 0.8;
							var nHeight = screen.height * 0.8;
							strURL = strURL.replace("/site.asmx/Dialog?", "/gate.asmx/WebExecute?");
							if (strOperation.indexOf("_window") != -1)
								window.open(strURL, strTarget, "scrollbars=yes,left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",resizable=yes");
							else
							{
								var oTop = window.dialogArguments;
								while (oTop != null && oTop.dialogArguments != null)
									oTop = oTop.dialogArguments;
								oTop = (oTop == null ? window : oTop);

								if (oTop.frHeader.top.navigator.sxPrintState == "busy")
								{
									alert("Печать предыдущего пакета документов не закончена.\r\nПожалуйста подождите.");
									return;
								}
								oTop.frHeader.document.all.PrintSpan.innerHTML = "<iframe name=Print style='position:absolute;left:-1000;top:-1000;height:100;width:100;' onload='document.parentWindow.PrintDocument(this);'></iframe>";
								
								if (oButton.IsLockEditor == "true")
								{
									DisabledForm(oForm, true);
									oLastDisableForm = null;
									oTop.frHeader.document.body.all["Print"].DisableForm = oForm;
								}

								oTop.frHeader.document.frames.Print.document.location.href = strURL;
							}
						}
					}
				}
				else
				{
					//	Добавляем в форму первым пустой параметр, который может быть затерт IE
					if (oForm.elements[0] != null && oForm.elements[0].name != "nop")
					{
						var oInput = window.document.createElement("<input type=hidden name=nop value=nop>");
						oForm.insertBefore(oInput, oForm.firstChild);
					}

					//	Если операция содержит суфикс _inself то результат помещаем в наше окно
					if (strOperation.indexOf("_inself") != -1)
					{
						oForm.target = "";
						var strAction = document.location.href.split('?')[0];
						strAction = SetURLParam(strAction, "address", oForm.elements["address"].value);
						oForm.action = MakeURL(strAction);
					}


					top.bIsSave = true;
					top.bIsDialogResized = false;

					//	Если выполяется изменение поля
					if (IsExecuteOnChangeOnProcess)
					{
						//	Запускаем процес отложенного выполнения зпроса
						oLastExecuteForm = oForm;
						oLastExecuteForm.IsLockEditor = oButton.IsLockEditor;
						setTimeout("FinishExecOperation()", 100);

						//	Блокируем кнопки редактора
						if (oButton.IsLockEditor == "true")
							DisabledForm(oForm, true);

        			                //	Прерываем выполнение функции
						return false;
					}

					//	Разблокируем форму перед выполнением запроса
					//	Нельзя оставлять незаблокированные кнопки, т.к. иногода происходит 
					//	двойное ее нажатие
					DisabledForm(oForm, false);

					//	Отсылаем запрос на сервер
					oForm.submit();
					if (oButton.IsLockEditor == "true")
						DisabledForm(oForm, true);
				}
				oForm.elements["address_operation"].value = oForm.OldOperation;
				oForm.elements["address"].value = oForm.OldAddress;
				try { oForm.elements["after_operation_action"].value = ""; } catch(e) {}
				try { oForm.elements["is_readonly"].value = oForm.OldIsReadOnly; } catch(e) {}
			}
		}
	}   	
	catch(e) {}
}

function FinishExecOperation()
{
	try
	{
		//	Если выполнение изменения поля еще в процессе, то откладываем еще
		if (IsExecuteOnChangeOnProcess)
		{
			setTimeout("FinishExecOperation()", 100);
			return;
		}

		//	Если уже можно начинать основной процесс выполнения
		if (oLastDisableForm != null)
			DisabledForm(oLastDisableForm, false);

		oLastExecuteForm.submit();
		if (oLastExecuteForm.IsLockEditor == "true")
			DisabledForm(oLastExecuteForm, true);
	
		oLastExecuteForm.elements["address_operation"].value = oLastExecuteForm.OldOperation;
		oLastExecuteForm.elements["address"].value = oLastExecuteForm.OldAddress;
		try { oLastExecuteForm.elements["after_operation_action"].value = ""; } catch(e) {}
		oLastExecuteForm = null;
	}   	
	catch(e) {}
}

var oLastFocusedElement = null;

function DisabledForm(oForm, bIsDisabled, bIsPassButtons)
{
	try
	{
		//	Если нет заблокированных форм и хотим разблокировать, то ничего не делаем
		if (oLastDisableForm == null && !bIsDisabled)
			return;

		//	Если последняя заблокированная форма наша и мы хотим опять блокировать, то ничего не делаем
		if (oLastDisableForm == oForm && bIsDisabled)
			return;

		//	Если последняя заблокированная форма есть и она не наша и мы хотим опять блокировать, 
		//	то сначала разблокируем заблокированную форму а потом блокируем нашу
		if (oLastDisableForm != null && bIsDisabled && oLastDisableForm != oForm)
			DisabledForm(oLastDisableForm, false);

		if (bIsDisabled)
			oLastFocusedElement = document.activeElement;
    
		for(var nPos = 0; nPos < oForm.elements.length; nPos++)
		{	
			var oElement = oForm.elements[nPos];
			var strTagName = oElement.tagName.toUpperCase();

			if (strTagName == "INPUT" && oElement.type.toUpperCase() == "HIDDEN")
				continue;

			if (bIsPassButtons && strTagName == "BUTTON")
				continue;

			if (bIsDisabled)
			{
				if (strTagName == "INPUT")
				{
					if (oElement.type.toUpperCase() != "FILE")
					{
						oElement.originalOnKeyDown = oElement.onkeydown;
						oElement.onkeydown = NoFocus;
					}
					else
					{
				    	oElement.originalReadonly = oElement.readOnly;
				    	oElement.readOnly = true;
					}
					oElement.style.filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity=70, FinishOpacity=0, Style=0, StartX=0,  FinishX=100, StartY=0, FinishY=100)";
				}
				else
				{
			    	oElement.originalDisabled = oElement.disabled;
			    	oElement.disabled = true;
				}
			}
			else
			{
				if (strTagName == "INPUT")
				{
					if (oElement.type.toUpperCase() != "FILE")
						oElement.onkeydown = oElement.originalOnKeyDown;
					else
						oElement.readOnly = oElement.originalReadonly;
					oElement.style.filter = null;
				}
				else
			    	oElement.disabled = oElement.originalDisabled;
			}
		}
		oLastDisableForm = (bIsDisabled ? oForm : null);

		if (!bIsDisabled && oLastFocusedElement != null)
		{
			oLastFocusedElement.focus();
			oLastFocusedElement = null;
		}

	}   	
	catch(e) {}
}

function NoFocus()
{
	window.event.cancelBubble = true;
	window.event.returnValue = false;
	return false;
}

function HeaderClick()
{
	try
	{
		if (event.srcElement.tagName.toUpperCase() != "BUTTON")
			return;

		oTD = CheckCell(window.event.srcElement);
		if (IsPressCtrl())	
		{
			if (IsPressShift())
				SetFilterEx(oTD);
			else
				GetFilter(oTD);
		}
		else
			SortBy(oTD);
	}   	
	catch(e) {}
}
 
var oResizeCol = null;
var oResizeColScreenPos = null;

function StartColumnResize(event)
{
	if (event.srcElement.tagName.toUpperCase() != "TD")
		return;

	oResizeCol = event.srcElement;
	oResizeColScreenPos = event.screenX;
	oResizeCol.setCapture(true);
}

function EndColumnResize()
{
	try
	{
		if (oResizeCol == null)
			return;

		oRect = oResizeCol.getBoundingClientRect();
		nColWidth = !IsListStacked()? oRect.right - oRect.left : oResizeCol.clientWidth;

		GetHeaderCell(oResizeCol, document.all['oTableData']).style.width = 
			oResizeCol.style.width = nColWidth + (event.screenX - oResizeColScreenPos);

		var rectTable = document.all['oTableData'].getBoundingClientRect();
		var nColWidthPercent = (nColWidth + (event.screenX - oResizeColScreenPos)) * 100 / (rectTable.right - rectTable.left);

		var strEditorID = (oResizeCol.FieldEditor != null ? oResizeCol.FieldEditor : (document.body.EditorID != null ? document.body.EditorID : "DEFAULT"));

		var strURL = "/gate.asmx/WebExecute?address=" + document.body.Address.split(":")[0] + "&address_operation=customize";
		strURL = SetURLParam(strURL, "_type", "Editor:" + strEditorID);
		strURL = SetURLParam(strURL, "_row_id", oResizeCol.FieldName);
		strURL = SetURLParam(strURL, "_attribute", "width");
		strURL = SetURLParam(strURL, "_value", parseInt("" + nColWidthPercent) + "%");
		strURL = MakeURL(strURL);
		Download.startDownload(strURL, onCustomizeDone);

		oResizeCol.releaseCapture();
		oResizeCol = null;

		window.event.cancelBubble = true;
		window.event.returnValue = false;
		return false;
	}   	
	catch(e) {}
}

function RestoreDefault(oTD)
{
	try
	{
		var strEditorID = (oTD.FieldEditor != null ? oTD.FieldEditor : (document.body.EditorID != null ? document.body.EditorID : "DEFAULT"));

		var strURL = "/gate.asmx/WebExecute?address=" + document.body.Address.split(":")[0] + "&address_operation=customize";
		strURL = SetURLParam(strURL, "_type", "Editor:" + strEditorID);
		strURL = SetURLParam(strURL, "_is_restore_default", "true");
		strURL = MakeURL(strURL);
		Download.startDownload(strURL, onCustomizeRestoreDefaultDone);
	}   	
	catch(e) {}
}

function onCustomizeDone(strText)
{
}

function onCustomizeRestoreDefaultDone(strText)
{
	document.location.href = document.location.href;
}

function SortBy(oTD, bIsPressAlt, bIsRemove)
{
	try
	{
		if (!oTD.Sorted)
			return;
		var strFullOrder = oTD.parentElement.parentElement.parentElement.Order;
		if (strFullOrder == null || (!IsPressAlt() && !bIsPressAlt))
			strFullOrder = "";
		var aOrder = strFullOrder.split(',');
		var strField = (oTD.OrderField != null ? oTD.OrderField.split(' ')[0] : "[" + oTD.FieldName + "]");
		var strOrderField = strField + (oTD.SortType != null ? " " + oTD.SortType : "");
		
		var strNewOrder = "";
		var nCount = 0;
		for(var nPos = 0; nPos < aOrder.length; nPos++)
		{
			if (aOrder[nPos].indexOf(strField) == -1)
				strNewOrder += (strNewOrder != "" ? "," : "") + aOrder[nPos];
			else
				if (!bIsRemove)
					strNewOrder += (strNewOrder != "" ? "," : "") + strOrderField;
		}
		if (strNewOrder.indexOf(strOrderField) == -1 && !bIsRemove)
			strNewOrder += (strNewOrder != "" ? "," : "") + strOrderField;
		oTable = oTD.parentElement.parentElement.parentElement;
		oTD.document.location.href = SetURLParam(oTD.document.location.href, "address_order", strNewOrder);
	}   	
	catch(e) {}
}

function ClearAllSort()
{
	try
	{
		document.location.href = SetURLParam(document.location.href, "address_order", "");
	}   	
	catch(e) {}
}
 
function GetFilter(oTD, isOnlyFocus)
{
	try
	{
		if (oTD.isFilter || !oTD.Filtered)
		{
			alert("Колонка не поддерживает фильтрацию");
			return;
		}
	
		oTD.Header = oTD.innerHTML;
		var strFilterValue = (oTD.Filter == null ? "" : oTD.Filter);

		if (oTD.ChoiseSet != null && oTD.ChoiseSet != "")
		{
			var strSelect = "<select id=Filter style='width=100%;' onkeypress='return SetFilter(this);' onchange='return SetFilter(this);' onblur='parentElement.isFilter = false; parentElement.innerHTML = parentElement.Header;' onclick='event.cancelBubble=true; return false;'>";
			strSelect += "<option></option>";
			
			var oChoiseSet = oTD.ChoiseSet.split('|');
			for (var nPos = 0; nPos < oChoiseSet.length; nPos++)
			{
				var oChoise = oChoiseSet[nPos].split(';');

				strSelect += "<option value='=$$$" + oChoise[0] + "'";
				strSelect += ("=$$$" + oChoise[0] == strFilterValue ? " selected" : "") + ">" ;
				strSelect += (oChoise.length > 1 ? oChoise[1] : oChoise[0]);
				strSelect += "</option>";
			}

			strSelect += "</select>";

			oTD.innerHTML = strSelect;
			oTD.children[0].select();
			if (defValue != null)
				oTD.children[0].value = defValue;
		}
		else
		if (oTD.ColType == "date")
			oTD.innerHTML = "<input id=Filter class=clsSingleBorder value='" + strFilterValue + "' onkeypress='return SetFilter(this);' onblur='var oTD = parentElement; oTD.isFilter = false; oTD.innerHTML = oTD.Header;' onkeydown='if (window.event.keyCode == 40 && !top.Calendar.isOpen) CalendarShow(this); if (top.Calendar.isOpen) {window.event.returnValue = false; event.cancelBubble=true; return false;}' value='" + strFilterValue + "' onclick='event.cancelBubble=true; return false;'>";
		else
			oTD.innerHTML = "<input id=Filter class=clsSingleBorder onkeypress='return SetFilter(this);' onkeyup='return SelectRowByData(" + oTD.cellIndex + ", this.value);' onblur='parentElement.isFilter = false; parentElement.innerHTML = parentElement.Header;' value='" + strFilterValue + "' onclick='event.cancelBubble=true; return false;'>";

		oTD.isFilter = true;
		if (isOnlyFocus)
		{
			oTD.children[0].focus();
			oTD.children[0].select();
		}
		else
			setTimeout("document.all['Filter'].focus();document.all['Filter'].select();", 100);
	}   	
	catch(e) {}
}

function SetFilterEx(oTD)
{
	try
	{
		if (oTD.isFilter || !oTD.Filtered)
		{
			alert("Колонка не поддерживает фильтрацию");
			return;
		}

		var	strAddress = GetParamByUrl(window.document.location.href, "address"); 

		var strURL = oTD.document.parentWindow.MakeURL("/site.asmx/Dialog?address=system.hi/IntelligentFilter:NEW&current_address=" + strAddress + "&column_name=" + oTD.FieldName + "&current_filter=" + (oTD.Filter != null ? oTD.Filter : "") + "&is_dialog=true" + (oTD.IsRelated != null ? "&_is_related=" + oTD.IsRelated : ""));
		top.LastEnterFieldPos = 0;
		var strFilter = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
		strFilter = strFilter.replace("<BODY>", "").replace("</BODY>", "");

		for (var nLine = 0; nLine < (IsListStacked() ? oTableHeader.rows.length : 1); nLine++)
		{
			var oCells = oTableHeader.rows[nLine].cells;
			var strFilters = "";
			for(var nPos = 0; nPos < oCells.length; nPos++)
			{
				var strValue = (oCells[nPos] == oTD ? strFilter : oCells[nPos].Filter);
				if (strValue != null && strValue != "")
				{
					var strFilterField = (oCells[nPos].FilterField != null && oCells[nPos].FilterField != "" ? oCells[nPos].FilterField : oCells[nPos].FieldName);
					strFilters += "&filter_" + strFilterField + "=" + strValue.replace(/\+/gi, "%2B");
				}
			}
		}

		strURL = RemoveURLParamStartsWith(oTD.document.location.href, "address_first");
		oTD.document.location.href = RemoveURLParamStartsWith(strURL, "filter_") + strFilters;
	}   	
	catch(e) {}
}

function SetFilter(oInput)
{
	try                        
	{
		if (window.event.keyCode == 27)
		{
			var strHeader = oInput.parentElement.Header;
			oInput.parentElement.Header = "";
			oInput.parentElement.isFilter = false;
			oInput.parentElement.innerHTML = strHeader;
			oTableData.focus();
		}

		if (window.event.keyCode != 13 && window.event.keyCode != 0)
			return;

		var strFilterValue = oInput.value;
		if (oInput.tagName.toUpperCase() == "SELECT")
			strFilterValue = oInput.options[oInput.selectedIndex].value;

		var strFilters = "";
		for (var nRowNdx = 0; nRowNdx < oTableHeader.rows.length; nRowNdx++)
		{
			var oCells = oTableHeader.rows[nRowNdx].cells;
			for (var nPos = 0; nPos < oCells.length; nPos++)
			{
				var strValue = (oCells[nPos] == oInput.parentElement ? strFilterValue : oCells[nPos].Filter);
				if (strValue != null && strValue != "")
				{
					var strFilterField = (oCells[nPos].FilterField != null && oCells[nPos].FilterField != "" ? oCells[nPos].FilterField : oCells[nPos].FieldName);
					strFilters += "&filter_" + strFilterField + "=" + strValue.replace(/\+/gi, "%2B");
				}
			}
		}
		strURL = RemoveURLParamStartsWith(oInput.document.location.href, "address_first");
		strURL = RemoveURLParamStartsWith(strURL, "filter_") + strFilters;
		oTableHeader.document.location.href = strURL;
	}   	
	catch(e) {}
}

function ClearFilters()
{
	try
	{
		document.location.href = RemoveURLParamStartsWith(document.location.href, "filter_");
	}   	
	catch(e) {}
}
 
function ClearFilter(oTD)
{
	try
	{
		var strFilterField = (oTD.FilterField != null && oTD.FilterField != "" ? oTD.FilterField : oTD.FieldName);
		document.location.href = RemoveURLParamStartsWith(document.location.href, "filter_" + strFilterField);
	}   	
	catch(e) {}
}

function SetValueAsFilter(oTD)
{
	try
	{
		var oHeaderTD = GetHeaderCell(window.SelectedRowCell);
		if (oHeaderTD.isFilter || !oHeaderTD.Filtered)
		{
			alert("Колонка не поддерживает фильтрацию");
			return;
		}

		var strURL = document.location.href;
		var strFilterField = (oHeaderTD.FilterField != null && oHeaderTD.FilterField != "" ? oHeaderTD.FilterField : oHeaderTD.FieldName);
		var filterValue = oTD.innerText;
		if (oHeaderTD.ChoiseSet != null && oHeaderTD.ChoiseSet != "")
		{
			var aPares = oHeaderTD.ChoiseSet.split('|');
			for (var i = 0; i < aPares.length; i++)
			{
				var aOption = aPares[i].split(';');
				if (filterValue == aOption[1])
				{
					filterValue = "=$$$" + aOption[0];
					break;
				}
			}
		}
		if (oHeaderTD.IsRelated)
			strURL = SetURLParam(strURL, "filter_" + strFilterField, filterValue);
		else
			strURL = SetURLParam(strURL, "filter_" + strFilterField, "=$$$" + filterValue + "$$$");
		strURL = RemoveURLParamStartsWith(strURL, "address_first");
		document.location.href = strURL;
	}   	
	catch(e) {}
}

function SelectTabBySrc(strTabDataSrc, strTabDataPage)
{
	try
	{
		oTable = document.all['oChildTabs'];
		if (oTable == null)
			return;

		var aListElements = oTable.all;
		if (oTable.Lines != 1)
			aListElements = oTable.rows[0].cells[0].children[oTable.Lines - 1].all;

		var oFirstElement = null;
		for(nElement = 0; nElement < aListElements.length; nElement++)
		{
			var oElement = aListElements[nElement];
			if (oElement == null || (oElement.data_src == null && oElement.page == null))
				continue;

			oFirstElement = (oFirstElement == null ? oElement : oFirstElement);
			if ((strTabDataSrc == null && strTabDataPage == null) || 
				( oElement.data_src == strTabDataSrc && oElement.data_src != null) ||
				( (oElement.page == strTabDataPage || oElement.pageID == strTabDataPage) && oElement.data_src == null) )
					return SelectTab(oElement);
		}

		return SelectTab(oFirstElement);
	}   	
	catch(e) {}
}

function SelectTab(oTabDiv)
{
	try
	{
		if (IsPressShift())
			return false;

		oTable = oTabDiv;
		while(oTable != null && oTable.className != "clsTabTable")
			oTable = oTable.parentElement;

		top.TabDataSrc = oTabDiv.data_src;
		top.TabDataPage = oTabDiv.page;
		if (oTable.Lines != 1)
		{
			var oCell = oTable.rows[0].cells[0];
			if (oCell.lastChild.innerHTML.indexOf(oTabDiv.outerHTML) == -1)
			{
				var oFirst = oCell.firstChild;
				oCell.removeChild(oFirst);
				oCell.appendChild(oFirst);
				for(var nChild = 0; nChild < oCell.children.length; nChild++)
					oCell.children[nChild].className = (nChild < oCell.children.length - 1 ? "clsTabLine" : "");
			}
		}
		var bIsFocusList = (oTable.select_tab != null);
		if (oTable.select_tab != oTabDiv || IsPressCtrl())
		{
			if (oTable.select_tab != null && IsPressCtrl())
				OpenURL(oTabDiv.data_src);
			else
			{
				if (oTable.select_tab != null)
					oTable.select_tab.parentElement.className = 'clsNavPage';
				oTabDiv.parentElement.className = 'clsNavPageActual';
				var strNewSrc = MakeURL(oTabDiv.data_src) + "&is_child=true" + (bIsFocusList ? "&is_focus_list=true" : "");
				if (oTabDiv.data_src != null)
					oTable.all['data_frame'].src = strNewSrc;

				var oHidePage = null;
				var oShowPage = null;
				if (oTable.select_tab != null && oTable.select_tab.page != null)
					oHidePage = oTable.all[oTable.select_tab.page];
				if (oTabDiv.page != null)
					oShowPage = oTable.all[oTabDiv.page];

				if (oHidePage != oShowPage)
				{
					if (oHidePage != null) oHidePage.style.display = "none";
					if (oShowPage != null) oShowPage.style.display = "block";
				}

				//	Инициализируем все iframe 
				var aIFrames = oShowPage.all.tags('iframe');
				for(var nIFrame = 0; nIFrame < aIFrames.length; nIFrame++)
					if (aIFrames[nIFrame].data_src != null)
						aIFrames[nIFrame].src = MakeURL(aIFrames[nIFrame].data_src);
					
				oTable.select_tab = oTabDiv;
				window.document.focus();
			}
		}
	}   	
	catch(e) {}
}

function ClickCheckboxTD(oTD, bIsChangeStateChilds)
{
	try
	{
		if (window.event.srcElement == oTD) 
			oTD.children[1].checked = !oTD.children[1].checked;
		oTD.children[0].value = (oTD.children[1].checked ? oTD.true_value : oTD.false_value);
		
		if (bIsChangeStateChilds)
			SetChildState(oTD);
	}   	
	catch(e) {}
}

function ClickRadioTD(oTD)
{
	try
	{
		if (window.event.srcElement == oTD && !oTD.previousSibling.children[0].checked) 
		{
			oTD.previousSibling.children[0].checked = true;
			oTD.previousSibling.children[0].fireEvent("onchange");
		}
	}   	
	catch(e) {}
}

function SetChildState(oTD)
{
	try
	{
		var oParent = oTD.parentElement;
		if (oParent == null)
			return;
		for(var nPos = 0; nPos < oParent.all.length; nPos++)
		{
			if (oParent.all[nPos] != oTD && oParent.all[nPos].parentElement != oTD)
				oParent.all[nPos].disabled = !oTD.children[1].checked;
		}
	}   	
	catch(e) {}
}

//========= Inplace edit support functions ===========================================================================

top.InplaceEditCell = null;

function InplaceEdit(oRow, oCell)
{
	try
	{
		if (oCell == null || top.InplaceEditCell != null)
			return false;
		var nCellPos = oCell.cellIndex;               
		var bIsReadOnly = GetHeaderCell(oCell).ReadOnlyField;
		if (bIsReadOnly != null && bIsReadOnly.toUpperCase() == "TRUE")
			return false;
		var strFieldName = GetHeaderCell(oCell).FieldName;
		if ((strFieldName.indexOf("is_") != 0) && (strFieldName.indexOf("[is_") != 0) && (strFieldName.indexOf(".is_") == -1))
			return false;
		var strSetValue = (oCell.className == "U" ? "true" : "false");
		top.InplaceEditCell = oCell;
		var strURL = "/gate.asmx/WebExecute?address=" + RowAddress(oRow)+ "&address_operation=inplace_update&_" + strFieldName + "=" + strSetValue + "&field=" + strFieldName + "&out_driver=Value";
		strURL = MakeURL(strURL);
		oInplaceEdit.startDownload(strURL, onInplaceEditDone);
		return true;
	}   	
	catch(e) {}
}

function onInplaceEditDone(strText)
{
	try
	{
		if (strText.indexOf('MESSAGE|') == 0)
		{
			top.InplaceEditCell = null;
			alert(strText.substring(8));
			return
		}

		if (strText.indexOf('<body') != -1)
		{
			top.InplaceEditCell = null;
			alert(strText.replace(/<.*?>/gi,""))
			return
		}

		if (top.InplaceEditCell == null)
			return;
		var nCellPos = top.InplaceEditCell.cellIndex;               
		var strFieldName = GetHeaderCell(top.InplaceEditCell).FieldName;
		var bResult = (strText.indexOf("True") != -1);
		top.InplaceEditCell.className = (bResult ? "B" : "U");
		top.InplaceEditCell = null;
	}   	
	catch(e) {}
}

//========= Event support functions ===========================================================================

function SelectStart(event)
{
	try
	{
		var ob = (event != null) ? event.srcElement : window.event.srcElement;

		var bIsContentEditable = false;
		var obCheck = ob;
		while (!bIsContentEditable && obCheck != null)
		{
			bIsContentEditable = (obCheck.contentEditable == "true");
			obCheck = obCheck.parentElement;
		}

		if (ob == null || ob.tagName.toUpperCase() == "INPUT" || ob.tagName.toUpperCase() == "TEXTAREA" ||
			bIsContentEditable)
			return true;

		window.event.cancelBubble = true;
		window.event.returnValue = false;
		return false;
	}
	catch (e) {}
	return true;
} 

function onContextMenu(event)
{
	try
	{
		var ob = event.srcElement;
		if (IsPressCtrl() || (ob != null && ob.MenuView == null && 
			(ob.tagName.toUpperCase() == "INPUT" || ob.tagName.toUpperCase() == "TEXTAREA") && !IsPressAlt()))
			return true;

		var oRow = CheckRow(event.srcElement);

		var oTable = CheckTable(oRow);
		var strSelectedIDs = oTable == null? "" : GetSelectedRowIDs(oTable);
		strSelectedIDs = strSelectedIDs.indexOf(",") < 0? "" : "&selected_ids=" + strSelectedIDs;
		
		if (!IsSelected(oRow))
			SelectRow(oRow);
		else
			SetCellSelected(event.srcElement);

		var strMenuView = null;
		var strMenuConfigView = null;
		var strRelationAddress = null;
		var strAddress = RowAddress(window.SelectedRow);

		if (ob.id == 'sfd')
			try {strRelationAddress = ob.parentElement.nextSibling.children[0].Address.replace("address=", ""); } catch(e) {}

		while (ob != null && (strMenuView == null || strMenuConfigView == null || strAddress == null))
		{   	
			if (strMenuView == null)	strMenuView = ob.MenuView;
			if (strMenuConfigView == null)	strMenuConfigView = ob.MenuConfigView;
			if (strAddress == null)		strAddress = ob.Address;
			ob = ob.parentElement;
		}

		if (strAddress == null || strAddress == "")
			strAddress = GetParamByUrl(window.document.location.href, "address"); 
		if (strMenuView == null) strMenuView = "";
		if (strMenuConfigView == null || strMenuConfigView == "")
			strMenuConfigView = "MENUITEMS-CONFIGURATION_EDIT";

		if (strAddress != null && (strMenuView != "" || IsPressAlt()))
		{
			if (IsPressAlt())
				ShowPopupMenu(strAddress.split(':')[0] + ':' + strMenuConfigView, event);
			else
			{
				if (strMenuView != null && strMenuView.indexOf("#RELATION#:") == 0)
				{
					strMenuView = strMenuView.replace("#RELATION#:", "")
					strAddress = strRelationAddress;
					var strShowField = GetParamByUrl("?" + strAddress, "show_field");
					if (strShowField != null && strMenuView.indexOf("&_name_field=") == -1)
						strMenuView += "&_name_field=" + strShowField;				
				}
				if (strMenuView != null && strMenuView.indexOf("#FIELD-") == 0)
				{
					var strObjectEl = strMenuView.split(':')[0].replace("#FIELD-", "").replace("#", "");
					strAddress = document.forms[0].elements['_' + strObjectEl].value;
					strMenuView = strMenuView.replace("#FIELD-" + strObjectEl + "#:", "");
				}

				ShowPopupMenu(strAddress.split(':')[0] + ':' + strMenuView + strSelectedIDs + (oTable != null ? "&operations=" + oTable.Operations : ""), event);
			}
			return false;
		}
	}   	
	catch(e) {}

	return false;
}

//========= Mouse functions ===========================================================================

function onMouseOver(event)
{
	try
	{
		var ob = event.srcElement;
		while (ob != null)
		{   	
			if ((ob.title != null && ob.title != "") || (ob.tagName.toUpperCase() == "A"))
			{
				window.status = (ob.title != '' ? ob.title : ob.innerText);
				window.event.cancelBubble = true;
				return true;
			}
			ob = ob.parentElement;
		}
	}   	
	catch(e) {}

	return true;
}

function onMouseOut(event)
{
	return true;
}


function onTabMouseOver(event)
{
	try
	{
		var ob = event.srcElement.parentElement.parentElement;
		if (ob.className == "clsNavPage")
			ob.className = "clsNavPageOver";
	}   	
	catch(e) {}

	return true;
}

function onTabMouseOut(event)
{
	try
	{
		var ob = event.srcElement.parentElement.parentElement;
		if (ob.className == "clsNavPageOver")
			ob.className = "clsNavPage";
	}   	
	catch(e) {}

	return true;
}

//========= SID support functions ===========================================================================

function UserLogoff()
{
	try
	{
		top.frHeader.document.location.href = MakeURL("/gate.asmx/WebExecute?address=" + top.strBaseAddress + "&address_operation=logoff&out_driver=Value");
		var aThrow = null;
		top.SID = "";
		Delay(500);
	}
	catch(e) {}
}

function GetSID()
{
	var strSID = "";
	try { strSID = (top.SID == null ? "" : top.SID); } catch(e) {}
	strSID = (strSID == "" ? GetParamByUrl(window.document.location.href, "sid") : strSID);
	return strSID;
}

function MakeURL(strUrl, bIsDisableDebugMode)
{
	var strNewURL = strUrl;
	if (GetDebugMode())
	{
    	strNewURL = SetURLParam(strNewURL, "context_debug_mode", "True");
		if (bIsDisableDebugMode == null || bIsDisableDebugMode)
			SetDebugMode(false);
	}
	strNewURL = SetURLParam(strNewURL, "__query_for_vi", "true");
	return SetURLParam(strNewURL, "sid", GetSID());
}

function OpenURL(strUrl, bIsOpenInNew)
{
	try
	{
		if (IsPressShift())
			return false;
		if (IsPressCtrl() || bIsOpenInNew)
			window.open(MakeURL(strUrl), '', 'channelmode=0,toolbar=0,location=0,fullscreen=0,scrollbars=1,resizable=1,titlebar=1;top=1;left=1;', 0);
		else
			document.location.href = MakeURL(strUrl);
		window.event.cancelBubble = true;
	}
	catch(e) {}
	return false;
}

//========= URL support functions ===========================================================================

function SetURLParam(strUrl, strKey, strValue)
{
	try
	{
		var aParts = strUrl.split('?');
		var strQuery = (aParts.length > 1 ? aParts[1] : "");
		var strNewQuery = "";
		var aParams = strQuery.split('&');
		var bIsPresent = false;
		for(var nPos = 0; nPos < aParams.length; nPos++)
		{
			if (aParams[nPos] == "")
				continue;
			strNewQuery += (strNewQuery == "" ? "?" : "&");
			var nEqPos = aParams[nPos].indexOf("=");
			var strName = (nEqPos != -1 ? aParams[nPos].substr(0, nEqPos) : aParams[nPos]);
			if (strName == strKey)
			{
				bIsPresent = true;
				strNewQuery += strKey + "=" + strValue; 
			}
			else
				strNewQuery += aParams[nPos];
		}
		if (!bIsPresent)
		{
			strNewQuery += (strNewQuery == "" ? "?" : "&");
			strNewQuery += (strKey + "=" + strValue); 
		}
		return aParts[0] + strNewQuery;
	}
	catch(e) {}

	return "";
}

function GetParamByUrl(strUrl, strKey)
{
	var aParts = strUrl.split('?');
	var strQuery = (aParts.length > 1 ? aParts[1] : "");
	var aParams = strQuery.split('&');
	for(var nPos = 0; nPos < aParams.length; nPos++)
	{
		var aParts = aParams[nPos].split('=');
		if (aParts[0] == strKey)
			return unescape(aParts.length > 1 ? aParts[1] : ""); 
	}
	return "";
}

function RemoveURLParamStartsWith(strUrl, strKey)
{
	var aParts = strUrl.split('?');
	strUrl = aParts[0];
	var strQuery = (aParts.length > 1 ? aParts[1] : "");
	var aParams = strQuery.split('&');
	strQuery = "";
	for(var nPos = 0; nPos < aParams.length; nPos++)
	{
		var aParts = aParams[nPos].split('=');
		if (aParts[0].indexOf(strKey) == 0)
			continue;
		strQuery += (nPos == 0 ? "?" : "&") + aParams[nPos];
	}
	return strUrl + strQuery;
}
//========= Menu support functions ===========================================================================

function ShowMenu(strMenu, strURL, strRootAddress)
{
	try
	{
		var ob = window.event.srcElement;
		if (ob != null && ob.Submenu != null)
		{
			ShowPopupMenu(strRootAddress + ':MENUITEMS-' + ob.Submenu, window.event, -window.event.offsetX - 1, ob.clientHeight - window.event.offsetY + 1);
			return;
		}
	}
	catch(e) {}
}

var oPopup = null;
top.oPopupEventSrc = null;
top.oPopupOpenerWindow = null;

try
{ 
	if (top.oPopup == null)
	{
		top.oPopup = new Object();
		top.oPopup.window = window.createPopup();
	}
}
catch(e) {};

try { closePopup(); } catch(e) {}

function closePopup()
{
	try
	{
		try { top.oPopup.window.hide(); } catch(e) {}
		top.oPopup.window = window.createPopup();
	}
	catch(e) {};

	return true;	
}

function ShowPopupMenu(strAddress, event, nOffsetX, nOffsetY)
{
	try
	{
		top.oPopupEventSrc = (event != null ? event.srcElement : null);
		top.oPopupOpenerWindow = window;
		var strURL = MakeURL("/gate.asmx/WebExecute?address=" + strAddress + "&out_driver=MENU", false);
		top.oPopup.xPos = (event.clientOffsetX != null ? event.clientOffsetX : event.screenX - top.screenLeft);
		top.oPopup.yPos = (event.clientOffsetY != null ? event.clientOffsetY : event.screenY - top.screenTop);
		if (nOffsetX != null) top.oPopup.xPos += nOffsetX;
		if (nOffsetY != null) top.oPopup.yPos += nOffsetY;
		Download.startDownload(strURL, onDownloadMenuDone);
	}
	catch(e) {}
}

function onDownloadMenuDone(strText, nWidth, nHeight)
{
	try
	{
		var oPopupBody = top.oPopup.window.document.body;
		oPopupBody.innerHTML = strText;

		top.oPopup.window.show(top.oPopup.xPos, top.oPopup.yPos, 0, 0, oPopupBody);
		nWidth = (nWidth == null ? oPopupBody.scrollWidth : nWidth);
		nHeight = (nHeight == null ? oPopupBody.scrollHeight : nHeight);
		top.oPopup.window.show(top.oPopup.xPos, top.oPopup.yPos, nWidth, nHeight, oPopupBody);
	}
	catch(e) {}
}

function ShowMessage(strMessage, nWidth, nHeight)
{
	try
	{
		var oPopupBody = top.oPopup.window.document.body;
		oPopupBody.innerHTML = "<table style='width:100%;height:100%;border:1px solid black;background-color:buttonface;font-family: tahoma, ms sans-serif, arial;font-size:12px'><tr><td align=center valign=middle style='padding:10px;cursor:default' onselectstart='return false;'>" + strMessage + "</td></tr></table>";
		top.oPopup.window.show((screen.width - nWidth) / 2 - top.screenLeft, (screen.height - nHeight) / 2 - top.screenTop, nWidth, nHeight, oPopupBody);
	}
	catch(e) {}
}

top.obActiveTree = null;
top.obActiveElement = null;

function ShowTreeMenu(obTree, event)
{
	try
	{
		top.obActiveElement = event.srcElement;
		while(top.obActiveElement != null && top.obActiveElement.type != "leaf" && top.obActiveElement.type != "parent")
			top.obActiveElement = top.obActiveElement.parentElement;
		top.obActiveTree = obTree;
		var oLeaf = top.obActiveElement.children[2];

		if (top.obActiveElement != null)
		{
			var strAddress = oLeaf.id.split(':')[0] + ":MENUITEMS-TREE";
			ShowPopupMenu(strAddress, event);
			return false;
		}
	}
	catch(e) {}
}

function ExecutePopupOperation(event)
{
	try
	{
		var oElement = event.srcElement;
		while (oElement != null && oElement.Operation == null)
    		oElement = oElement.parentElement;
		
		closePopup();

		if (oElement.IsLockEditor == "true")
			DisabledForm(document.forms[0], true);

		if (oElement.IsSaveRecord == "true" && oElement.Operation != "execute_function:update")
			ExecOperation(document.forms[0].elements[0], "update", "", "", "edit");

		switch (oElement.Operation.split(':')[0])
		{
			case "tree":			top.oPopupOpenerWindow.ExecuteTreeOperation(oElement); break;
			case "table":			top.oPopupOpenerWindow.ExecuteTableOperation(oElement.Operation, oElement); break;
			case "table_data":		top.oPopupOpenerWindow.ExecuteTableDataOperation(oElement.Operation); break;
			case "table_header":	top.oPopupOpenerWindow.ExecuteTableHeaderOperation(oElement.Operation); break;
			case "execute":			top.oPopupOpenerWindow.ExecuteObjectOperation(oElement.Operation); break;
			case "execute_function":top.oPopupOpenerWindow.ExecuteObjectOperation(oElement.Operation, true, oElement); break;
			case "execute_dialog":	top.oPopupOpenerWindow.ExecuteObjectOperation(oElement.Operation, false, oElement); break;
			case "execute_window":	top.oPopupOpenerWindow.ExecuteWindow(oElement.Operation, oElement); break;
			case "execute_window_sx":	top.oPopupOpenerWindow.ExecuteWindowSX(oElement.Operation, oElement); break;
			case "execute_print":	top.oPopupOpenerWindow.ExecutePrint(oElement.Operation); break;
			case "execute_print_sx":	top.oPopupOpenerWindow.ExecutePrintSX(oElement.Operation); break;
			case "execute_event":	top.oPopupOpenerWindow.ExecuteEvent(oElement); break;
			case "configuration":	top.oPopupOpenerWindow.ExecuteConfigurationOperation(oElement.Operation, true); break;
			case "url":				window.open(MakeURL(oElement.Operation.substring(4))); break;
			case "dialog":			top.LastEnterFieldPos = 0; window.showModalDialog(MakeURL(oElement.Operation.substring(7)), top, "dialogWidth: 400px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no"); break;
			case "set_value":		
			case "append_value":	
			case "insert_value":	top.oPopupOpenerWindow.ExecuteSetValueOperation(oElement); break
			case "js":				top.oPopupOpenerWindow.ExecuteJSOperation(oElement.Operation); break;
			case "LockInterface":
			{
				top.frMain.document.body.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=40);";
				top.frLeft.document.body.style.backgroundImage = "url(/editor/images/lock_back.gif)";
				top.frRight.document.body.style.backgroundImage = "url(/editor/images/lock_back.gif)";
				top.frHeader.document.body.style.backgroundImage = "url(/editor/images/lock_back.gif)";
				top.SID = window.showModalDialog('/site.asmx/Logon', top, 'dialogWidth: 417px; dialogHeight: 230px; edge: Raised; center: Yes; help: No; resizable: No; status: No; scroll: No');
				top.frLeft.document.body.style.backgroundImage = "";
				top.frRight.document.body.style.backgroundImage = "";
				top.frHeader.document.body.style.backgroundImage = "";
				top.frMain.document.body.style.filter = null;
				if (top.SID == null)
					top.document.location.href = top.document.location.href;
				break;
			}
			case "NewInterface":
			{
				var strURL = MakeURL(top.document.location.href.split('?')[0]);
				window.open(strURL, '', 'channelmode=0,toolbar=0,location=0,fullscreen=0,scrollbars=1,resizable=1,titlebar=1;top=1;left=1;', 0);
				break;
			}
			case "ExitInterface":	top.document.location.href = '/site.asmx/Empty'; break;
			case "Help":			ExecOperation(null, "help"); break;
		}

		event.cancelBubble = true;
		event.returnValue = false;
	}
	catch(e) {}

	return false;
}

function ExecuteTreeOperation(oElement)
{
	var Operation = oElement.Operation;
	var strView = oElement.View;
	if (top.obActiveElement == null || top.obActiveTree == null)
		return;

	switch (Operation)
	{
		case "tree:Open": 		top.obActiveTree.SelectElement(top.obActiveElement, null, strView); break;
		case "tree:Refresh":	if (top.obActiveElement.children[2].xmlsrc != "") top.obActiveTree.RefreshChildren(top.obActiveElement); break;
		case "tree:Expand": 	top.obActiveTree.ExpandNode(top.obActiveElement); break;
		case "tree:Collapse":	top.obActiveTree.CollapseNode(top.obActiveElement); break;
	}
}

function ExecuteJSOperation(Operation)
{
	switch (Operation)
	{
		case "js:cut": 			document.execCommand("Cut", false, null); break;
		case "js:copy": 		document.execCommand("Copy", false, null); break;
		case "js:paste": 		document.execCommand("Paste", false, null); break;
		case "js:clear": 		document.execCommand("SelectAll", false, null); document.execCommand("Cut", false, null); break;
		case "js:select_all": 		document.execCommand("SelectAll", false, null); break;
		case "js:ShowAllFieldValues": 	ShowAllFieldValues(); break;
	}
}

function ExecuteTableOperation(Operation, oMenuElement)
{
	if (top.oPopupEventSrc != null)
	{
		var oRow = CheckRow(top.oPopupEventSrc);
		if (!IsSelected(oRow))
			top.oPopupOpenerWindow.SelectRow(oRow);
	}

	switch (Operation)
	{
		case "table:Open": 				TableKeyUp(13, oMenuElement); break;
		case "table:New": 				TableKeyUp(45, oMenuElement); break;
		case "table:Delete": 			TableKeyUp(46, oMenuElement); break;
		case "table:Refresh": 			document.location.href = SetURLParam(document.location.href, "selected_row_index", (window.SelectedRow != null ? window.SelectedRow.rowIndex : "")); break;
		case "table:Copy": 				CopyRow(window.SelectedRow, oMenuElement); break;
		case "table:CopyRow": 			CopyToClipboard(window.SelectedRow); break;
		case "table:CopyCell": 			CopyToClipboard(top.oPopupEventSrc); break;
		case "table:SetValueAsFilter":	SetValueAsFilter(window.SelectedRowCell); break;
	}
}

function ExecuteTableHeaderOperation(Operation)
{
	var oTD = (top.oPopupEventSrc != null ? top.oPopupEventSrc : window.event.srcElement);
	while(oTD != null && oTD.tagName.toUpperCase() != "TD")
		oTD = oTD.parentElement;

	var oTD = GetHeaderCell(oTD);

	switch (Operation)
	{
		case "table_header:Sort": 			SortBy(oTD); break;
		case "table_header:AddSort":		SortBy(oTD, true); break;
		case "table_header:ClearSort":		SortBy(oTD, true, true); break;
		case "table_header:ClearAllSort":	ClearAllSort(); break;
		case "table_header:Filter": 		GetFilter(oTD); break;
		case "table_header:FilterEx": 		SetFilterEx(oTD); break;
		case "table_header:ClearFilters":	ClearFilters(); break;
		case "table_header:ClearFilter":	ClearFilter(oTD); break;
		case "table_header:ClearFilter":	ClearFilter(oTD); break;
		case "table_header:RestoreDefault":	RestoreDefault(oTD); break;
	}
}

function ExecuteTableDataOperation(Operation)
{
 	if (top.oPopupEventSrc == null || top.oPopupEventSrc.parentElement == null)
		return;

	var oLink = top.oPopupEventSrc.parentElement;
	switch (Operation)
	{
		case "table_data:SaveAsExcel": 	DownloadExcel(oLink); break;
		case "table_data:SendAsExcel": 	
		case "table_data:SendAsCompressExcel":
		{
			var strOldURL = oLink.URL;
			var strEmail = window.prompt("Укажите e-mail на который Вы хотите отправить данный документ", "");
			if (strEmail == null || strEmail == "")
				return;

			var strURL = SetURLParam(oLink.URL, "transport", (Operation == "table_data:SendAsExcel" ? "SMTP" : "SMTP_ZIP"));
			strURL = SetURLParam(strURL, "smtp_transport_to", strEmail);
			strURL = SetURLParam(strURL, "smtp_transport_subject", "Данные");
			oLink.URL = MakeURL(strURL); 
			oLink.click();
			oLink.URL = strOldURL; 
			alert("Данные отосланны на указанный Вами e-mail")
			break;
		}
		case "table_data:SaveAsXML":
		{
			var strOldURL = oLink.URL;
			var strURL = SetURLParam(oLink.URL, "out_driver", "XML");
			var strURL = SetURLParam(oLink.URL, "out_content_type", "text/xml");
			oLink.URL = MakeURL(strURL); 
			oLink.click();
			oLink.URL = strOldURL; 
			break;
		}
		case "table_data:ShowAsXML":
		{
			var strURL = SetURLParam(document.location.href, "out_driver", "XML");
			window.open(strURL); 
			break;
		}
		case "table_data:CopyToClipboard": CopyToClipboard(); break;
	}
}

function ExecuteObjectOperation(Operation, IsFunction, Container)
{
	var aOperation = Operation.split(':');
 	if (top.oPopupEventSrc == null || top.oPopupEventSrc.parentElement == null || aOperation.length < 2)
		return;

	var strOperation = aOperation[1].toLowerCase();
	if (strOperation == "" || strOperation == "add" || strOperation == "update" || 
		strOperation == "delete" || strOperation == "close" || strOperation == "help") 
	{
		ExecOperation(document.forms[0].elements[0], strOperation, Container.Message, Container.View, Container.AfterOperationAction); 
		return;
	}

 	if (top.frLeft != null  && top.frLeft.document == window.document)
		top.frRight.document.location.href = MakeURL(SetURLParam(top.obActiveElement.children[2].children[0].href, "address_operation", aOperation[1]));
	else
	{	
		var strURL = document.location.href; 
		if (strURL.indexOf("WebExecute") == -1)
			strURL = MakeURL("/gate.asmx/WebExecute?");

		var strAddress = Container.Address;
		if (strAddress != null && strAddress != "")
			strURL = SetURLParam(strURL, "address", strAddress)
	
		if (window.SelectedRow != null || window.SelectedCard != null)
		{
			//	Берем адрес текущей выбранной записи
			if (strAddress == null || strAddress == "")
				strAddress = RowAddress(window.SelectedRow != null ? window.SelectedRow : window.SelectedCard);

			//	Если это групповая операция
			if (IsGroupOperation(aOperation[1]))
			{
				//	Определяем все идентификаторы выделенных записей
				var oTable = CheckTable(window.SelectedRow);
				var strSelectedIDs = GetSelectedRowIDs(oTable);
				//	Формируем адрес для выполнения операции
				strAddress = oTable.DataAddress + "-" + strSelectedIDs;
			}
			strURL = SetURLParam(strURL, "address", strAddress)
		}

		//	Если задано View? то подменяем оригинальное на заданное
		if (Container != null && Container.View != null && Container.View != "")
		{
			var strAddress = GetParamByUrl(strURL, "address");
			strAddress = strAddress.split(':')[0] + ':' + Container.View;
			strURL = SetURLParam(strURL, "address", strAddress)
		}

		strURL = SetURLParam(strURL, "address_operation", aOperation[1]);
		if (Operation.split(':')[0] == "execute_dialog")
			strURL = SetURLParam(strURL, "is_dialog", "true");
		strURL = SetURLParam(strURL, "after_operation_action", "refresh");

		//	Если заданы дополнительные параметры, то добавляем их в запрос
		if (Container != null && Container.Params != null && Container.Params != "")
			strURL += "&" + Container.Params;

		switch (Operation.split(':')[0])
		{
			case "execute":				document.location.href = strURL; break;
			case "execute_function":	
			{
				if (!Container.IsExecuteUseForm)
				{
					//	Если вызывается групповая операция - то делаем все по сложному
					if (IsGroupOperation(strOperation))
						ExecConfirmOperation(window.SelectedRow, strOperation, "", Container)
					else
						//	иначе по старому
						document.frames.Execute.document.location.href = strURL; 
				}
				else
				{
					if (strAddress != "")
						document.forms[0].elements["address"].value = strAddress;
					document.forms[0].elements["after_operation_action"].value = "refresh";
					var bIsOldLockEditor = document.forms[0].elements[0].IsLockEditor;
					document.forms[0].elements[0].IsLockEditor = Container.IsLockEditor;
					ExecOperation(document.forms[0].elements[0], strOperation, Container.Message); 
					document.forms[0].elements[0].IsLockEditor = bIsOldLockEditor;
				}
				break;
			}
			case "execute_dialog":
			{
				strURL = strURL.replace("/gate.asmx/WebExecute", "/site.asmx/Dialog");
				top.LastEnterFieldPos = 0;
				var oResult = top.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 200px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no"); 
				AnalyzeDialogResult(oResult, document);
				break;
			}
			case "execute_window":
			{
				var nLeft = screen.width * 0.05, nTop = screen.height * 0.05, nWidth = screen.width * 0.8, nHeight = screen.height * 0.8;
				window.open(strURL, "_blank", "scrollbars=yes,left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",resizable=yes");
				break;
			}
		}
	}
}

function ExecuteWindow(Operation, Container)
{
	var aAdresses = Operation.substr(Operation.indexOf(":") + 1).split(";");
	var nLeft = screen.width * 0.05, nTop = screen.height * 0.05, nWidth = screen.width * 0.8, nHeight = screen.height * 0.8;
	for (i = aAdresses.length - 1; i >= 0; i--)
	{
		var strAddress = aAdresses[i];
		if (strAddress == "" || strAddress == "get")
			ExecuteObjectOperation(Operation, false, Container);
		else
		{
			var strURL = MakeURL("/gate.asmx/WebExecute?" + strAddress);
			window.open(strURL, "_blank", "scrollbars=yes,left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",resizable=yes");
			nLeft += 16;
			nTop += 16;
		}
	}
	return;
}

function ExecuteWindowSX(Operation, Container)
{
	//	для сохранения перед печатью
	//ExecOperation(document.forms[0].elements[0], "update", Container.Message, "", "edit");

	var host = Operation.indexOf("&host=");
	host = host >= 0? Operation.substr(host + 6) : "";
	
	var aAdresses = Operation.substr(Operation.indexOf(":") + 1).split(";");
	var nLeft = screen.width * 0.05, nTop = screen.height * 0.05, nWidth = screen.width * 0.8, nHeight = screen.height * 0.8;
	for (i = aAdresses.length - 1; i >= 0; i--)
	{
		var strAddress = aAdresses[i];
		if (strAddress == "" || strAddress == "get")
			ExecuteObjectOperation(Operation, false, Container);
		else
		{
			var strURL = MakeURL("http://www.meadroid.com/editor/sx_print.aspx?print_url=" + escape(host + "/gate.asmx/WebExecute?" + strAddress));
			window.open(strURL, "_blank", "scrollbars=yes,left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",resizable=yes");
			nLeft += 16;
			nTop += 16;
		}
	}
}

function ExecutePrint(Operation)
{
	var oTarget = window.dialogArguments != null? window.dialogArguments.frHeader : top.frHeader;
	var strURL = Operation.substring(Operation.indexOf(":") + 1);
	var strURL = MakeURL("/gate.asmx/WebExecute?" + strURL);
	oTarget.document.all.PrintSpan.innerHTML = "<iframe name=Print style='position:absolute;left:-1000;top:-1000;height:100;width:100;' onload='document.parentWindow.PrintDocument(this);'></iframe>";
	oTarget.document.frames.Print.document.location.href = strURL;
}

function ExecutePrintSX(Operation)
{

	var host = Operation.indexOf("&host=");
	host = host >= 0? Operation.substr(host + 6) : "";

	var oTarget = window.dialogArguments != null? window.dialogArguments.frHeader : top.frHeader;
	var strURL = Operation.substring(Operation.indexOf(":") + 1);
	var strURL = MakeURL("http://www.meadroid.com/editor/sx_print.aspx?print_url=" + escape(host + "/gate.asmx/WebExecute?" + strURL) + "&is_direct_print=true");
	if (oTarget.top.navigator.sxPrintState == "busy")
	{
		alert("Печать предыдущего пакета документов не закончена.\r\nПожалуйста подождите.");
		return;
	}
	oTarget.document.all.PrintSpan.innerHTML = "<iframe name=Print style='position:absolute;left:-1000;top:-1000;height:500;width:500;'></iframe>";
	oTarget.document.frames.Print.document.location.href = strURL;
}


function ExecuteConfigurationOperation(Operation)
{
	var strEditorID = "";
	var strFieldID = "";

	var strAddress = GetParamByUrl(window.document.location.href, "address").replace(/%2f/g, "/"); 
	//	Если в параметрах есть указание на редактирование значения адреса из поля редактора
	if (top.oPopupEventSrc != null && Operation.indexOf("#ADDRESS#") != -1)
	{
		//	Если поле редактора для которого вызвали контекстное меню адрес то берем его в качестве адреса
		if (top.oPopupEventSrc.name.indexOf("_address") != -1)
			strAddress = top.oPopupEventSrc.value;
		else
		if (top.oPopupEventSrc.id == 'sfd')
		{
			try {strAddress = top.oPopupEventSrc.parentElement.nextSibling.children[0].Address.replace("address=", ""); } catch(e) {}
			strEditorID = strFieldID = top.oPopupEventSrc.value + " ";
		}

		Operation = Operation.replace("#ADDRESS#", "");
	}

	var oAddress = strAddress.split(':')[0].split('/');
	var strConfAddress = "system.hi";
	for(var nPos = 0; nPos < oAddress.length; nPos++)
		strConfAddress += "/Objects-" + oAddress[nPos].split('-')[0];

	if (Operation.indexOf("configuration:") == 0)
	{
		if (Operation == "configuration:ExecuteWithDebug")
		{
			SetDebugMode(true);
			window.document.frames.Execute.document.location.href = MakeURL(document.location.href);
			SetDebugMode(false);
			setTimeout("ExecuteConfigurationOperation('configuration:DEBUGINFO');", 2000);
			return;
		} 

		if (Operation == "configuration:SetDebugMode")
		{
			SetDebugMode(GetDebugMode() == true ? false : true);
			window.document.body.focus();
			return;
		} 

		if (Operation.indexOf("configuration:Profile-") != -1)
		{
			var strOper = Operation.replace("configuration:Profile-", "");
			var strURLExec = MakeURL("/gate.asmx/WebExecute?address=system.hi/Profiler/All&address_operation=" + strOper);
			var strURLGet = MakeURL("/gate.asmx/WebExecute?address=system.hi/Profiler/All");
			if (strOper != "get")
				window.document.frames.Execute.document.location.href = strURLExec;
			window.open(strURLGet, 'Profile', 'channelmode=0,toolbar=0,location=0,fullscreen=0,scrollbars=1,resizable=1,titlebar=1;top=1;left=1;', 0);
        		return;
		} 


		try
		{
			if (window.SelectedRowCell != null && oTableHeader != null)
			{
				var oHeaderTD = GetHeaderCell(window.SelectedRowCell);
				strFieldID = (oHeaderTD.FieldID != null ? oHeaderTD.FieldID : oHeaderTD.FieldName);
				strEditorID = (oHeaderTD.FieldEditor != null ? oHeaderTD.FieldEditor : strEditorID);
			}
	
			var oElement = top.oPopupEventSrc;
			if (strFieldID == "")
			{
				strFieldID = (oElement != null && oElement.name != null ? oElement.name.substring(1) : "");
				if (strFieldID == "")
				{
					var oInput = (oElement.id == "sfd_text" ? FindElement(oElement, 'sfd') : oElement.previousSibling);
					strFieldID = (oInput != null && oInput.name != null ? oInput.name.substring(1) : "");
				}
			}
		
			while (strEditorID == "" && oElement != null)
			{
				strEditorID = (oElement.EditorID != null ? oElement.EditorID : strEditorID);
				oElement = oElement.parentElement;
			}
		}
		catch(e) {}

		strConfAddress += "/" + Operation.substring(14);
		if (Operation == "configuration:LastErrors") strConfAddress = "system.hi/System/LastErrors:LASTERRORS";
		if (Operation == "configuration:DEBUGINFO") strConfAddress = "system.hi/System/DEBUGINFO:DEBUGINFO";
		if (Operation == "configuration:UDIBuilder") strConfAddress = "system.hi/UDIBuilder:NEW&_OriginalAddress=" + strAddress;
		if (Operation == "configuration:ReloadCurrentConfig") strConfAddress = "system.hi/System/All&address_operation=reload_config&_ObjectAddress=" + strAddress;
		if (Operation == "configuration:ReloadAllСonfig") strConfAddress = "system.hi/System/All&address_operation=reload_config";
		strConfAddress = strConfAddress.replace("/Editors-CURRENT", "/Editors-" + strEditorID);
		strConfAddress = strConfAddress.replace("/EditorFields-CURRENT", "/EditorFields-" + strFieldID);
		strConfAddress = strConfAddress.replace("/Relations-CURRENT", "/Relations-" + strFieldID);
		top.LastEnterFieldPos = 0;
		if (Operation != "configuration:ReloadCurrentConfig" && Operation != "configuration:ReloadAllСonfig")
		{
			var strURL = MakeURL("/site.asmx/Dialog?address=" + strConfAddress);
			var oResult = window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 300px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");

			if (oResult != null)
			{
				var oDoc = (top.frames.DialogMainFarame != null ? top.frames.DialogMainFarame.document : top.frRight.document);
				oDoc.location.href = SetURLParam(oDoc.location.href, "rnd", Math.random()); 
			}
		}
		else
			window.document.frames.Execute.document.location.href = MakeURL("/gate.asmx/WebExecute?address=" + strConfAddress);
		window.document.body.focus();
	}
}

function ExecuteEvent(oElement)
{
	try
	{
		var aOperation = oElement.Operation.split(':');
		var oEvent = (aOperation.length > 1 ? aOperation[1] : "");
		if (oEvent != "" && top.oPopupEventSrc != null)
			top.oPopupEventSrc.fireEvent(oEvent);
	}
	catch(e) {}
}

function ExecuteSetValueOperation(oElement)
{
	try
	{
		if (top.oPopupEventSrc != null)
		{
			switch (oElement.Operation.split(':')[0])
			{
				case "insert_value":
				{
					top.oPopupEventSrc.focus();
					//	Сохраняем старое содержимое буффера обмена
		    		var strOldClipboardData = window.clipboardData.getData("Text");
		    		//	Берем наши данные и заталкиваем их в буффур обмена
					var strValue = oElement.Operation.substring(13);
					window.clipboardData.setData("Text", strValue);
					//	Выталкиваем их из буфура в контрол
					window.document.execCommand('Paste');
					//	Востанавливаем старое значение буфера
					window.clipboardData.setData("Text", strOldClipboardData);
					return;
				}		
				case "append_value":
				{
					var strValue = oElement.Operation.substring(13);
					top.oPopupEventSrc.value += strValue;
					return;
				}		
				case "set_value":
				{
					var strValue = oElement.Operation.substring(10);
					top.oPopupEventSrc.value = strValue;
					return;
				}		
			}
		}
	}
	catch(e) {}
}

function OpenDialog(strURL)
{
	try
	{
		strURL = MakeURL(strURL);
		top.LastEnterFieldPos = 0;
		return window.showModalDialog(strURL, top, "dialogWidth: 500px; dialogHeight: 50px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
	}
	catch(e) {}
}

//============================	HTML functions ==============================================================

function EditHTML(oEditor)
{
	try
	{
		oEditor = oEditor.parentElement.previousSibling.children[0];
		var strEditorURL = (oEditor.EditorURL == null || oEditor.EditorURL == "" ? "/editor/editor.aspx" : oEditor.EditorURL);
		strEditorURL = SetURLParam(strEditorURL, "rnd", Math.random()); 
		window.showModalDialog(strEditorURL, oEditor, "dialogWidth: 800px; dialogHeight: 500px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: No; scroll: no");
	}
	catch(e) {}
}

function onPasteToHTML()
{
	var strText = window.clipboardData.getData("Text");
	var bIsAnyCRLFPresent = (strText.indexOf("\r") != -1) || (strText.indexOf("\n") != -1);
    strText = strText.replace(/\r/g, "").replace(/\n\n/g, "</P><P>").replace(/\n/g, "<BR>");

	//	Если это не был однострочный текст
	if (bIsAnyCRLFPresent)
	{
		//	Формируем начало параграфа в начале текста
		if (strText.indexOf("</P>") == 0)  strText = strText.substring(4);
		if (strText.indexOf("<BR>") == 0)  strText = strText.replace("<BR>", "<P>");
		if (strText.indexOf("<P>") != 0)   strText = "<P>" + strText;
	}

    window.clipboardData.setData("Text", strText);
}

var bIsEditHTMLPreviewModify = false;

function onHiddenHTMLChange(oInput)
{
	if (bIsEditHTMLPreviewModify != true)
		oInput.nextSibling.innerHTML = oInput.value;
}

function onEditHTMLPreview(oDiv)
{
	bIsEditHTMLPreviewModify = true;
	oDiv.previousSibling.value = oDiv.innerHTML;
	bIsEditHTMLPreviewModify = false;
	return true;
}

//============================	Other functions ==============================================================

function GetValueFromResult(strResult, strAttr)
{
	try
	{
		var oDiv = window.document.createElement("DIV");
		oDiv.innerHTML = strResult.toLowerCase().replace(/body/g, 'div');
   		var strValue = oDiv.children[0].getAttribute(strAttr.toLowerCase());
		oDiv.removeNode(true);
		return strValue;
	}
	catch(e) {}
}

function Delay(nMillisec)
{ 
	var then = new Date().getTime();
	var now = new Date().getTime(); 
	while((now - then) < nMillisec)
		now = new Date().getTime();
}

function CopyToClipboard(srcElement)
{
	if (srcElement == null)
		srcElement = CheckRow(window.SelectedRow).parentElement.parentElement;
	
	if (srcElement != null)
	{
		var strText = Trim(srcElement.outerHTML);
		if (strText.indexOf("<TR") == 0)
			strText = "<TABLE>" + strText + "</TABLE>";
		if (strText.indexOf("<TD") == 0 || strText.indexOf("<SPAN") == 0)
			strText = srcElement.innerText;
		window.clipboardData.setData("Text", strText);
	}
}

function GetMenuAddress(ob)
{
	try
	{
		var strMenuView = null;
		var strAddress = null;
		while(ob != null && (strMenuView == null || strAddress == null))
		{   	
			if (strMenuView == null)	strMenuView = ob.MenuView;
			if (strAddress == null)		strAddress = ob.Address;
			ob = ob.parentElement;
		}
		if (strMenuView != null && strAddress != null)
			return strAddress.split(':')[0] + ':' + strMenuView;
	}   	
	catch(e) {}

	return "";
}

function ShowButtonMenu(ob, strOperation, strAdditionalParams)
{
	try
	{
		var strAddress = GetMenuAddress(ob);
		if (strAddress != null && strAddress != "")
		{
			var MyEvent = new Object();
			var Pos = FindElementPos(ob);
			MyEvent.srcElement = window.event.srcElement;
			MyEvent.clientOffsetX = Pos.X;
			MyEvent.clientOffsetY = Pos.Y + ob.offsetHeight;
			strAddress += "&button_operation=" + strOperation;
			strAddress += "&is_readonly=" + GetParamByUrl(window.document.location.href, "is_readonly");
			strAddress += "&preview_mode=" + GetParamByUrl(window.document.location.href, "preview_mode");
			if (strAdditionalParams != null && strAdditionalParams != "")
				strAddress += strAdditionalParams;

			ShowPopupMenu(strAddress, MyEvent);
			return false;
		}
	}   	
	catch(e) {}

	return true;
}

function ShowFunctionButtonMenu(ob)
{
	try
	{
		var strAdditionalParams = "";
		var aInFunctionButtons = document.all.tags("InFunction");
		if (aInFunctionButtons != null)
		{
			for(var nButton=0; nButton < aInFunctionButtons.length; nButton++)
			{
				var oTag = aInFunctionButtons[nButton];
				strAdditionalParams += (strAdditionalParams != "" ? ";" : "") + (oTag.ReadOnly != null ? "-" : "") + oTag.Name;
			}
		}
		strAdditionalParams = (strAdditionalParams != "" ? "&buttons=" : "") + strAdditionalParams;


		return ShowButtonMenu(ob, "", strAdditionalParams);
	}   	
	catch(e) {}

	return true;
}

function FindElementPos(srcElement)
{
	var Pos = new Object();
	var oRect = srcElement.getBoundingClientRect();
	Pos.X = oRect.left - event.clientX + event.screenX - top.screenLeft;
	Pos.Y = oRect.top - event.clientY + event.screenY - top.screenTop;
	return Pos;
}

function DownloadExcel(oA)
{
	try
	{
		if (parseInt(oA.AllCount) > parseInt(oA.MaxDownloadForExcel))
			alert("Количество записей в списке превышает допустимое для выгрузки в Excel (" + oA.MaxDownloadForExcel + " записей).\r\nВоспользуйтесь фильтром для отбора нужных записей и повторите выгрузку.")
		else
		{
			ShowMessage("Идет формирование и загрузка данных в Excel файл", 300, 80);
			window.document.frames.DownloadExcelFrame.document.location.href = MakeURL(oA.URL);
		}
	}
	catch(e) {}

	window.event.cancelBubble = true;
	window.event.returnValue = false;
	return false;
}

function GetTopWindow()
{
	try
	{
		var oTop = window.dialogArguments;
		while (oTop != null && oTop.dialogArguments != null)
			oTop = oTop.dialogArguments;
		oTop = (oTop == null ? top : oTop);

		return oTop;
	}   	
	catch(e) {}

	return null;
}

function IsGroupOperation(strOperation)
{
	var nAmp = strOperation.indexOf("&");
	var nGroup = strOperation.indexOf("_group");
	return nGroup > 0 && nGroup == (nAmp >= 0? nAmp : strOperation.length) - 6;
}

function ShowEditorDialog(strURL)
{
	var oResult = window.showModalDialog(strURL + '&rnd=' + Math.random(), null, 'dialogWidth:500px; dialogHeight:500px; center:yes; help:yes; resizable:yes; status:no; scroll:yes');
	if (oResult != null)
		document.location.href = document.location.href;
}

//	====================================	Stacked List Functions	===================================
function IsListStacked(oElement)
{
	try
	{
		return (oTableHeader != null && oTableHeader.Stacked != null && oTableHeader.Stacked) || 
			(oTableData != null && oTableData.Stacked != null && oTableData.Stacked);
	}
	catch(e) {}
	
	return false;
}

function GetHeaderCell(CellOrIndex, oWhereToSearch)
{
	var nRowIndex = 0, nCellIndex = CellOrIndex;
	if (typeof(CellOrIndex) == "object" && CellOrIndex.tagName == "TD")
	{
		nRowIndex = IsListStacked() ? CellOrIndex.parentElement.StackLine : 0;
		nCellIndex = CellOrIndex.cellIndex;
	}
	return (oWhereToSearch == null? oTableHeader : oWhereToSearch).rows[nRowIndex].cells[nCellIndex];
}

function GetRecordRows(oRow)
{
	return oRow.parentElement.tagName == "TBODY" && !IsEmptyID(oRow.parentElement)?
		oRow.parentElement.childNodes : [oRow];
	
}

function IsCellInDataRow(oCell, oRow)
{
	if (!IsListStacked())
		return oCell.parentElement == oRow;

	var allTR = GetRecordRows(oRow);
	for (var i = 0; i < allTR.length; i++)
		if (oCell.parentElement == allTR[i])
			return true;
	return false;
}

function SetClassForRecordRows(oRow, className, classNameLine2)
{
	if (!IsListStacked())
		oRow.className = className;
	else
	{
		var allTR = GetRecordRows(oRow);
		for (var i = 0; i < allTR.length; i++)
			allTR[i].className = classNameLine2 != null && i > 0? classNameLine2 : className;
	}
}

function FindSameCellInRow(oRow, oCell)
{
	if (!IsListStacked())
		return oRow.cells[window.SelectedRowCell.cellIndex];
	else
	{
		var nIndexInRecord = window.SelectedRowCell.parentElement.StackLine;
		return oRow.parentElement.rows[nIndexInRecord == null? 0 : nIndexInRecord].cells[nIndexInRecord == null? 0 : window.SelectedRowCell.cellIndex];
	}
}

// ===== NAVIGATION
function GoToPreviousCell()
{
	if (!IsListStacked())
	{
		if (window.SelectedRowCell.previousSibling != null)
			SelectCell(window.SelectedRowCell.previousSibling);
		else
			SelectCell(window.SelectedRowCell.parentElement.lastChild);
	}
	else
	{
		if (window.SelectedRowCell.previousSibling != null)
			SelectCell(window.SelectedRowCell.previousSibling);
		else
		{
			var oSubRow = window.SelectedRowCell.parentElement;
			if (oSubRow.previousSibling != null)
				SelectCell(oSubRow.previousSibling.lastChild);
			else
				SelectCell(oSubRow.parentElement.lastChild.lastChild);
		}
	}
}

function GoToNextCell()
{
	if (!IsListStacked())
	{
		if (window.SelectedRowCell.nextSibling != null)
			SelectCell(window.SelectedRowCell.nextSibling);
		else
			SelectCell(window.SelectedRowCell.parentElement.firstChild);
	}
	else
	{
		if (window.SelectedRowCell.nextSibling != null)
			SelectCell(window.SelectedRowCell.nextSibling);
		else
		{
			var oSubRow = window.SelectedRowCell.parentElement;
			if (oSubRow.nextSibling != null)
				SelectCell(oSubRow.nextSibling.firstChild);
			else
				SelectCell(oSubRow.parentElement.firstChild.firstChild);
		}
	}
}

function GoToPreviousRecord()
{
	if (!IsListStacked())
	{
		if (window.SelectedRow.parentElement.firstChild != window.SelectedRow.previousSibling)
			SelectRow(window.SelectedRow.previousSibling, true);
	}
	else
	{
		var oPrevTBODY = window.SelectedRow.parentElement.previousSibling;
		if (!IsEmptyID(oPrevTBODY))
			SelectRow(oPrevTBODY.firstChild, true);
	}
}

function GoToNextRecord()
{
	if (!IsListStacked())
	{
		if (window.SelectedRow.nextSibling != null)
			SelectRow(window.SelectedRow.nextSibling, false);
	}
	else
	{
		var oNextTBODY = window.SelectedRow.parentElement.nextSibling;
		if (oNextTBODY)
			SelectRow(IsEmptyID(oNextTBODY)? CheckTable(window.SelectedRow).lastChild.lastChild : oNextTBODY.firstChild, false);
	}
}

function GoToLastRecord()
{
	if (!IsListStacked())
		SelectRow(window.SelectedRow.parentElement.lastChild, false);
	else
	{
		var oLastTBODY = CheckTable(window.SelectedRow).lastChild;
		SelectRow(IsEmptyID(oLastTBODY)? oLastTBODY.lastChild : oLastTBODY.firstChild, false);
	}
}

function GoToFirstRecord()
{
	if (!IsListStacked())
		SelectRow(window.SelectedRow.parentElement.firstChild.nextSibling, true);
	else
	{
		var oFirstTBODY = CheckTable(window.SelectedRow).firstChild;
		while (oFirstTBODY && IsEmptyID(oFirstTBODY))
			oFirstTBODY = oFirstTBODY.nextSibling;
		if (oFirstTBODY)
			SelectRow(oFirstTBODY.firstChild);
	}
}

function IsEmptyID(obj)
{
	return obj == null || obj.id == null || obj.id.toString().length == 0;
}
//  ==================================== Lock/Unlock Functions ========================================

function UnlockRecord()
{
	try
	{
		if (top.bNoUnlockRecord)
			return;

		var strURL = "/gate.asmx/WebExecute?address=" + document.body.Address + "&out_driver=VALUE";
		strURL = SetURLParam(strURL, "address_operation", "unlock");
		strURL = MakeURL(strURL);

		var oDownload = GetTopWindow().document.all('Download');
		oDownload = (oDownload == null ? window.document.all('Download') : oDownload);
		oDownload.startDownload(strURL, onUnlockRecord);
	}   	
	catch(e) {}

	return true;
}

function onUnlockRecord(strText) {}

//  ==================================== Calendar Functions ========================================

function CalendarInit()
{
	top.Calendar.date = null;
	top.Calendar.month = null;
	top.Calendar.year = null;

	top.Calendar.aMonths = [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ];
	top.Calendar.isSaturdayRed = true;
	//	Установить ограничения, принятые в MS SQL Server для типа datetime
	top.Calendar.minDate = new Date(1753, 0, 1);
	top.Calendar.maxDate = new Date(9999, 11, 31);
	top.Calendar.isOpen = false;

	CalendarCreatePopup();
}

function CalendarCreatePopup()
{
	top.Calendar.oPopup = window.createPopup();
	top.oPopupOpenerWindow = window;
	top.Calendar.pBody = top.Calendar.oPopup.document.body;
	top.Calendar.pBody.innerHTML = CalendarBuildCalendar();
	top.Calendar.pAll = top.Calendar.oPopup.document.all;
}

function CalendarGetState()
{
	top.Calendar.isOpen = top.Calendar.oPopup.isOpen;
}

function CalendarBuildCalendar()
{
	var content = "<body><style> \
		body, select, button, td, th {font: 11px tahoma, verdana} \
		.grid td, th {text-align:center; vertical-align:top} \
		td.slider {font-family:webdings; font-size:14px; color:buttontext; width:1px} \
		th {border-bottom:solid 1px buttonface} \
		span {width: 110%; height: 100%} \
		.selected {background-color: highlight; color:highlighttext} \
		.edge {color: inactivecaptiontext} \
		.hand {cursor: hand} \
		.red {color: red} \
		.today {border:solid 1px threedshadow; padding:0px} \
		.gray {background-color: buttonface} \
		</style>";
		
	content += "<div style='text-align:center; border:solid 1px black; padding:0px; cursor:default; width:152; height:145; overflow:hidden'>";
	
	content += "<table onkeydown='top.oPopupOpenerWindow.CalendarOnKey(event)' onselectstart='event.returnValue=false;' border=0 width='100%' cellpadding=0 cellspacing=0 class='gray'><tr> \
		<td align='left' class='slider'><nobr> \
			<span class='hand' onmouseup='top.oPopupOpenerWindow.CalendarSlideDate(top.Calendar.year - 1);' title='Предыдущий год'>&#55;</span><font style='font-size:4px'> </font><span class='hand' onmouseup='top.oPopupOpenerWindow.CalendarSlideDate(null, top.Calendar.month - 1);' title='Предыдущий месяц'>&#51;</span></nobr></td> \
			<td align='center' valign='middle'><b><nobr id='eMonthYear'>---<nobr></b></td> \
		<td align='right' class='slider'><nobr> \
			<span class='hand' onmouseup='top.oPopupOpenerWindow.CalendarSlideDate(null, top.Calendar.month + 1);' title='Следующий месяц'>&#52;</span><font style='font-size:4px'> </font><span class='hand' onmouseup='top.oPopupOpenerWindow.CalendarSlideDate(top.Calendar.year + 1);' title='Следующий год'>&#56;</span></nobr></td></tr>";
	content += "</table><div id='grid' onkeydown='top.oPopupOpenerWindow.CalendarOnKey(event)' style='height:106px'>---</div> \
		<table onkeydown='top.oPopupOpenerWindow.CalendarOnKey(event)' onselectstart='event.returnValue=false;' border=0 cellpadding=1 cellspacing=1 width='100%' class='gray'><tr><td width='100%' height='100%' align='center' valign='middle' onclick='top.oPopupOpenerWindow.CalendarSetDate();' ondblclick='top.oPopupOpenerWindow.CalendarSelectDate();' class='hand' title='Найти сегодняшнюю дату'>сегодня</td></tr> \
		</div></body>";
	return content;
}
	
function CalendarBuildGrid(argDate)
{
	top.Calendar.date = argDate.getDate();
	top.Calendar.month = argDate.getMonth();
	top.Calendar.year = argDate.getFullYear();
	
	var iDate;
	var sCurr = top.Calendar.year + " ";
	var sToday = new Date();
	sToday = sToday.getFullYear() + " " + sToday.getMonth() + "" + sToday.getDate();
	var oDate = new Date(argDate);
	oDate.setDate(1);
	var iWeekDay = (oDate.getDay() + 6) % 7;
	var content = "<table onkeydown='top.oPopupOpenerWindow.CalendarOnKey(event)' onselectstart='event.returnValue=false;' border=0 cellpadding=1 cellspacing=0 width='100%' class='grid'><tr><b><th>Пн</th><th>Вт</th><th>Ср</th><th>Чт</th><th>Пт</th><th"
		+ (top.Calendar.isSaturdayRed? " class='red'>Сб</th>" : ">Сб</th>") + "<th class='red'>Вс</th></b></tr><tr>";

	// previous month
	var oPrev = new Date(oDate);
	oPrev.setDate(1 - iWeekDay);
	var edgeMonth = top.Calendar.month - 1;
	for (iDate = oPrev.getDate(); iWeekDay > 0; iWeekDay--)
	{
		content += "<td onclick='top.oPopupOpenerWindow.CalendarSlideDate(null, " + edgeMonth + ", " + iDate + ")' class='edge"
			+ (sCurr + edgeMonth + iDate == sToday? "today'>" : "'>")
			+ iDate + "</td>";
		iDate++;
	}
	
	// current month
	for (iDate = 1; oDate.getMonth() == top.Calendar.month; oDate.setDate(++iDate))
	{
		iWeekDay = (oDate.getDay() + 6) % 7;
		var dateText = "<span";
		if (iDate == top.Calendar.date)
			dateText += " class='selected'";
		dateText += " id='e" + iDate + "' onclick='top.oPopupOpenerWindow.CalendarMarkDate(" + iDate + ")' ondblclick='top.oPopupOpenerWindow.CalendarSelectDate()'>"
			+ iDate + "</span>";
		if (iWeekDay >= (top.Calendar.isSaturdayRed? 5 : 6))
			dateText = "<font color='red'>" + dateText + "</font>";
		dateText = "<td"
			+ (sCurr + top.Calendar.month + iDate == sToday? " class='today'>" : ">")
			+ dateText + "</td>";
		content += dateText;
		if (iWeekDay == 6)
			content += "</tr><tr>";
	}
	
	// next month
	edgeMonth = top.Calendar.month + 1;
	for (iDate = 1; iWeekDay < 6; iWeekDay++)
	{
		content += "<td onclick='top.oPopupOpenerWindow.CalendarSlideDate(null, " + edgeMonth + ", " + iDate + ")' class='edge"
			+ (sCurr + edgeMonth + iDate == sToday? "today'>" : "'>")
			+ iDate + "</td>";
		iDate++;
	}
	content += "</tr></table>";
	return content;
}
	
function CalendarMarkDate(date)
{
	top.Calendar.pAll["e" + top.Calendar.date].className = "";
	top.Calendar.pAll["e" + date].className = "selected";
	top.Calendar.date = date;
}
	
function CalendarSlideDate(year, month, date, overflow)
{
	try
	{
		if (year == null) year = top.Calendar.year;
		if (month == null) month = top.Calendar.month;
		if (date == null) date = top.Calendar.date;
		CalendarSetDate(year, month, date, overflow);
	}
	catch (e) { CalendarSetDate(); }
}
	
function CalendarOnKey(event)
{
	event.cancelBubble = true;
	switch (event.keyCode)
	{
		case 37:	CalendarSlideDate(null, null, top.Calendar.date - 1, true);	break;
		case 39:	CalendarSlideDate(null, null, top.Calendar.date + 1, true);	break;
		case 38:	CalendarSlideDate(null, null, top.Calendar.date - 7, true);	break;
		case 40:	CalendarSlideDate(null, null, top.Calendar.date + 7, true);	break;
		case 33:	event.shiftKey || event.ctrlKey? CalendarSlideDate(top.Calendar.year - 1) : CalendarSlideDate(null, top.Calendar.month - 1);	break;
		case 34:	event.shiftKey || event.ctrlKey? CalendarSlideDate(top.Calendar.year + 1) : CalendarSlideDate(null, top.Calendar.month + 1);	break;
		case 13:	return CalendarSelectDate();
		case 27:	return CalendarHide();
	}
	top.Calendar.pAll.grid.focus();
}
	
function CalendarSetDate(year, month, date, overflow)
{
	var oDate;
	if (arguments.length == 0)
		oDate = new Date();
	else
	{
		oDate = new Date(year, month, date);
		if (!overflow && oDate.getDate() != date)
			oDate = new Date(year, month, date - oDate.getDate());
	}
	if (oDate < top.Calendar.minDate)
		oDate = new Date(top.Calendar.minDate);
	else if (oDate > top.Calendar.maxDate)
		oDate = new Date(top.Calendar.maxDate);
	top.Calendar.pAll.eMonthYear.innerHTML = top.Calendar.aMonths[oDate.getMonth()] + "&nbsp; " + oDate.getFullYear();
	top.Calendar.pAll.grid.innerHTML = CalendarBuildGrid(oDate);
}
	
function CalendarSplitDateString(str)
{
	var parts = str.split(".");
	var date = Math.abs(parseInt(parts[0], 10)), month = Math.abs(parseInt(parts[1], 10)) - 1, year = Math.abs(parseInt(parts[2], 10));
	if (isNaN(date + month + year))
		return null;
	if (date < 1) date = 1;
	else if (date > 31) date = 31;
	if (month < 0) month = 0;
	else if (month > 11) month = 11;
	if (year < 100)
		year += 2000;
	return [year, month, date];
}
	
function CalendarSelectDate()
{
	with (top.Calendar)
	{
		var strNewValue = CalendarZo(date) + "." + CalendarZo(parseInt(month) + 1) + "." + CalendarZo(year);
		if (destElement.value != strNewValue)
			destElement.is_changed = 'true';
		destElement.value = strNewValue;
		oPopup.hide();
		isOpen = false;
		destElement.focus();
	}
}
	
function CalendarZo(num)
{
	return num > 0 && num < 10? "0" + num : num;
}
	
function CalendarShow(anchorEl, width, height)
{
	if (anchorEl == top.Calendar.destElement && top.Calendar.isOpen)
		return CalendarHide();

	CalendarCreatePopup();
	top.Calendar.destElement = anchorEl;
	var parts = CalendarSplitDateString(anchorEl.value);
	parts == null? CalendarSetDate() : CalendarSetDate(parts[0], parts[1], parts[2]);
	top.Calendar.oPopup.show(0, anchorEl.offsetHeight, width == null? 152 : width, height == null? 145 : height, anchorEl);
	top.Calendar.isOpen = true;
	top.Calendar.pAll.grid.focus();
}
	
function CalendarHide()
{
	top.Calendar.oPopup.hide();
	top.Calendar.isOpen = false;
}

if (top.Calendar == null)
	top.Calendar = new Object();
CalendarInit();

//  ==================================== Toolbar Functions ========================================

function SetToolbarSize()
{
	try
	{
		var aRows = top.document.body.rows.split(',');
		var strNewRows = "";
		for(var nRow = 0; nRow < aRows.length; nRow++)
		{
			strRowHeight = aRows[nRow];
			if (nRow == 1)
			{
				var oToolBarBody = top.frToolBar.document.body;
				var oRect = oToolBarBody.all[oToolBarBody.all.length - 1].getBoundingClientRect();
				strRowHeight = oRect.bottom + 2;
			}
			strNewRows += (nRow > 0 ? "," : "") + strRowHeight;
		}
		top.document.body.rows = strNewRows;
		top.document.body.onresize = SetToolbarSize;
	}
	catch(e) {}
}

function DownloadToolbar()
{
	try
	{
		top.frToolBar.document.location.href = MakeURL('/site.asmx/ToolBarPanel');
	}
	catch(e) {}
}

//  ==================================== Print Functions ========================================

function PrintDocument(oFrame)
{
	try
	{
		var oDoc = oFrame.document.frames.Print.document;
		if (oDoc.body.innerText != "")
		{
			if (oDoc.body.Type == "Message")
				alert(oDoc.body.innerText);
			else
			{	
				oDoc.parentWindow.focus();
				oDoc.parentWindow.print();
			}
		}

		if (oFrame.DisableForm != null)
		{
			DisabledForm(oFrame.DisableForm, false);
			oFrame.DisableForm = null;
		}
	}
	catch(e) {}
}

//  ==================================== Debug Functions ========================================

function GetDebugMode()
{
	try
	{
		return (GetTopWindow().bIsDebugMode == true);
	}
	catch(e) {}
	
	return false;
}

function SetDebugMode(bIsEnabled)
{
	try
	{
		var oTop = GetTopWindow();
		oTop.bIsDebugMode = bIsEnabled;

		var oWndDoc = oTop.frToolBar.document;
		var oDebugMode = oWndDoc.all("DebugMode");
		if (GetDebugMode())
		{
			if (oDebugMode == null)
			{
				var oDebugMode = oWndDoc.createElement("<div>");
				oWndDoc.body.appendChild(oDebugMode);
			}
			oDebugMode.outerHTML = "<table class=clsToolbar id=DebugMode><tr><td class=clsToolbarBegin></td><td>Режим отладки - включён  </td><td><button class=clsToolbarBtn style='width:120px;' onClick='top.SetDebugMode(false)'>Отключить отладку</button></td></tr></table>";
		}
		else
			if (oDebugMode)
				oWndDoc.body.removeChild(oDebugMode);
	}
	catch(e) {}
}

function ShowAllFieldValues()
{
	try
	{
		var strResult = "";

		var thisForm = window.document.forms[0];
		var strURL = window.document.location.href;
		var strAddress = GetParamByUrl(window.document.location.href, "address");
		if (thisForm != null)
		{	
			strURL = strURL.split("?")[0] + "?";
			for(var nElement = 0; nElement < thisForm.elements.length; nElement++)
			{
				if (thisForm.elements[nElement].name == null || thisForm.elements[nElement].name == "")
					continue;
				var strValue = thisForm.elements[nElement].value;
				if (strValue.length > 64)
					strValue = strValue.substring(0, 60) + "...";
				strURL += "&" + thisForm.elements[nElement].name + "=" + strValue;
			}
			strAddress = thisForm.elements["address"].value;
		}
		
		strURL = SetURLParam(strURL, "address", "system.hi/UDIBuilder:FORM_PARAMS"); 
		strURL = SetURLParam(strURL, "address_operation", "get"); 
		strURL = SetURLParam(strURL, "original_address", strAddress); 
		strURL = SetURLParam(strURL, "is_dialog", "true"); 
		strURL = strURL.replace("/gate.asmx/WebExecute", "/site.asmx/Dialog");
		OpenDialog(strURL);
	}
	catch(e) { alert(e)}
}                                                
