/**
* HostCMS
*
* @author Hostmake LLC, http://www.hostcms.ru/
* @version 5.x
*/

// Предварительная загрузка изображений
if (document.images)
{
	img1 = new Image();
	img1.src = "/admin/images/shadow-b.png";

	img2 = new Image();
	img2.src = "/admin/images/shadow-l.png";

	img3 = new Image();
	img3.src = "/admin/images/shadow-lb.png";

	img4 = new Image();
	img4.src = "/admin/images/shadow-lt.png";

	img5 = new Image();
	img5.src = "/admin/images/shadow-r.png";

	img6 = new Image();
	img6.src = "/admin/images/shadow-rb.png";

	img7 = new Image();
	img7.src = "/admin/images/shadow-rt.png";

	img8 = new Image();
	img8.src = "/admin/images/shadow-t.png";
}

function row_over(object)
{
	if (object.className == 'row_table') object.className = 'row_table_over';
}

function row_out(object)
{
	if (object.className == 'row_table_over') object.className = 'row_table';
}

function row_over_odd(object)
{
	if (object.className == 'row_table_odd') object.className = 'row_table_over_odd';
}

function row_out_odd(object)
{
	if (object.className == 'row_table_over_odd') object.className = 'row_table_odd';
}


function menu_row_over(object)
{
	if (object.className == 'menu_out') object.className = 'menu_over';
}

function menu_row_out(object)
{
	if (object.className == 'menu_over') object.className = 'menu_out';
}

function SlideLayer(Num)
{
	var el = document.getElementById(Num);

	if (el.style.display=="block")
	{
		el.style.display="none";
	}
	else
	{
		el.style.display="block";
	}
}

// Функция для установки cookies
// name - имя параметра
// value - значение параметра
// expires - время жизни куки в секундах
// path - путь куки
// domain - домен
function setCookie (name, value, expires, path, domain, secure)
{
	// если истечение передано - устанавливаем время истечения на expires секунд вперед
	if (expires)
	{
		var date = new Date();
		expires = (expires * 1000) + date.getTime();
		date.setTime(expires);
	}

	VarCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + date.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

	document.cookie = VarCookie;
}


// Кроссбраузерная функция получения размеров экрана,
// используется в функции ShowLoadingScreen.
function getPageSize()
{
	var xScroll, yScroll;
	//document.all.myTR.clientHeight/2
	//var tagBody = document.all.body.clientHeight;

	//var tagBody = document.getElementById('bottomTd');
	//var tagBody =

	//document.bottomTd.offsetHeight;

	//alert(tagBody);

	if (window.innerHeight && window.scrollMaxY)
	{
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}
	else
	{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	//	console.log(self.innerWidth);
	//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight)
	{	// all except Explorer
		if(document.documentElement.clientWidth)
		{
			windowWidth = document.documentElement.clientWidth;
		}
		else
		{
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{ // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{ // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	}
	else
	{
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth)
	{
		pageWidth = xScroll;
	}
	else
	{
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
	return arrayPageSize;

}

// Получение информации о позиции скрола
function getScrollXY()
{
	var scrOfX = 0, scrOfY = 0;

	if (typeof(window.pageYOffset ) == 'number' )
	{
		//Netscape
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	}
	else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
	{
		//DOM
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	}
	else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
	{
		//IE6
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	return [ scrOfX, scrOfY ];
}

// Показ закладок на странице администрирования
function ShowLayer(AItemId, ASpan, FormID)
{
	// Получаем элемент формы
	var FormElement = document.getElementById(FormID);

	if (FormElement)
	{
		// Скрываем все tab-page'ы.
		element_array = FormElement.getElementsByTagName("div");

		if (element_array.length > 0)
		{
			for (var i = 0; i < element_array.length; i++)
			{
				if (element_array[i].getAttribute('id') == undefined)
				{
					continue;
				}

				if (element_array[i].getAttribute('id').search("tab_page_") != -1)
				{
					// Нельзя display: none; из-за визуального редактора
					element_array[i].style.display = "none";

					/*element_array[i].style.visitibility = "hidden";
					element_array[i].style.width = 0;
					element_array[i].style.height = 0;
					element_array[i].style.overflow = "hidden";*/
				}
			}
		}
	}

	var el = document.getElementById(AItemId);

	if (!el)
	{
		return false;
	}

	// Отображаем выбранный tab-page.
	el.style.display = "block";

	element_array = document.getElementsByTagName("li");

	// Если есть хотя бы один li
	if (element_array.length > 0)
	{
		for (var i = 0; i < element_array.length; i++)
		{
			if (element_array[i].getAttribute('id') == undefined)
			{
				continue;
			}

			// Неактивный
			if (element_array[i].getAttribute('id').search("id_tab_span_") != -1)
			{
				element_array[i].className = "";
			}

			// Активный
			if (element_array[i].getAttribute('id') == ASpan)
			{
				element_array[i].className = "current_li";
			}
		}

	}

	return true;
}

// =============================================
// Функции работы с меню
// =============================================
changeFontSizeTimer = new Array();

function HostCMSMenuOver(CurrenElementId, LevelMenu, ChildId)
{
	CurrenElement = document.getElementById(CurrenElementId);
	if (CurrenElementId == undefined)
	{
		return false;
	}

	decor(CurrenElementId, LevelMenu);
	if (ChildId != '')
	{
		ChildId = document.getElementById(ChildId);
		showHideMenu(ChildId);
	}
}

function HostCMSMenuOut(CurrenElementId, LevelMenu, ChildId)
{
	CurrenElement = document.getElementById(CurrenElementId);

	if (CurrenElementId == undefined)
	{
		return false;
	}

	unDecor(CurrenElementId, LevelMenu);
	if (ChildId != '')
	{
		ChildId = document.getElementById(ChildId);
		showHideMenu(ChildId);
	}
}

// Функции скрытия-открытия меню
function showHideMenu(ChildId)
{
	if (ChildId == undefined)
	{
		return false;
	}

	if (ChildId.style.display == "block")
	{
		ChildId.style.display = "none";
	}
	else
	{
		ChildId.style.display = "block";

		// получаем ширину выпадающего блока и устанавливаем её для верхней и нижней границы
		groupChildElements = ChildId.children;

		if (groupChildElements != undefined)
		{
			for (i = 0; i < groupChildElements.length; i++)
			{
				if(groupChildElements[i].className == 'b' | groupChildElements[i].className == 't')
				{
					groupChildElements[i].style.width = ChildId.clientWidth + 'px';
				}

				if(groupChildElements[i].className == 'r' | groupChildElements[i].className == 'l')
				{
					groupChildElements[i].style.height = ChildId.clientHeight + 'px';
				}
			}
		}
	}
}

// Функции оформления
function changeFontSize(CurrenElementId, change, limit)
{
	var CurrenElement = document.getElementById(CurrenElementId);

	if (CurrenElement)
	{
		var CurrFontSize = CurrenElement.style.fontSize ? parseInt(CurrenElement.style.fontSize) : 10;
		if (CurrFontSize != limit)
		{
			CurrenElement.style.fontSize = (CurrFontSize + change) + 'pt';
			changeFontSizeTimer[CurrenElementId] = setTimeout('changeFontSize("'+CurrenElementId+'", '+change+', '+limit+')', 1);
		}
	}
}

// Функция визуального оформления элементов меню
function decor(CurrenElementId, LevelMenu)
{
	var CurrenElemen = document.getElementById(CurrenElementId);

	if (LevelMenu == 1) // для первого уровня вложенности
	{
		CurrenElement.style.background = "url('/admin/images/line3.gif') repeat-x 0 100%";
		var child = CurrenElement.children;

		if (changeFontSizeTimer[CurrenElementId] != '')
		{
			clearTimeout(changeFontSizeTimer[CurrenElementId]);
		}
		changeFontSize(CurrenElement.id, 1, 13);

		// приподнемаем li при наведении
		//CurrenElementId.style.top = (navigator.userAgent.indexOf('Firefox') != -1)? '-2px':'-6px';
	}
	else // для второго уровня вложенности
	{

	}
}

// Функция визуального оформления элементов меню
function unDecor(CurrenElementId, LevelMenu)
{
	var CurrenElemen = document.getElementById(CurrenElementId);
	if (LevelMenu==1)
	{
		clearTimeout(changeFontSizeTimer[CurrenElementId]);
		CurrenElement.style.background = "url('/admin/images/line1.gif') repeat-x 0 100%";
		changeFontSize(CurrenElement.id, -1, 10);
	}
	else
	{
		//CurrenElementId.style.background = (navigator.userAgent.indexOf('MSIE') == -1)? 'url(/admin/images/fon_li.png) repeat-y 0 0':'url(/admin/images/fon_li.gif) repeat-y 0 0';
	}
}

function CreateWindow(windowId, windowTitle, windowWidth, windowHeight)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		// Создаем div для окна
		var fade_div = document.createElement("div");
		fade_div.setAttribute("id", windowId);
		var body = document.getElementsByTagName("body")[0];
		windowDiv = body.appendChild(fade_div);
	}

	// Тень
	windowDiv.className = "shadowed";

	if (windowWidth == '')
	{
		windowWidth = '300px';
	}

	windowDiv.style.width = windowWidth;

	if (windowHeight != '')
	{
		windowDiv.style.height = windowHeight;
	}

	var shadowed_tl = document.createElement("div");
	shadowed_tl.className = "tl";
	windowDiv.appendChild(shadowed_tl);

	var shadowed_t = document.createElement("div");
	shadowed_t.className = "t";
	windowDiv.appendChild(shadowed_t);

	var shadowed_tr = document.createElement("div");
	shadowed_tr.className = "tr";
	windowDiv.appendChild(shadowed_tr);

	var shadowed_l = document.createElement("div");
	shadowed_l.className = "l";
	windowDiv.appendChild(shadowed_l);

	var shadowed_r = document.createElement("div");
	shadowed_r.className = "r";
	windowDiv.appendChild(shadowed_r);

	var shadowed_bl = document.createElement("div");
	shadowed_bl.className = "bl";
	windowDiv.appendChild(shadowed_bl);

	var shadowed_b = document.createElement("div");
	shadowed_b.className = "b";
	windowDiv.appendChild(shadowed_b);

	var shadowed_br = document.createElement("div");
	shadowed_br.className = "br";
	windowDiv.appendChild(shadowed_br);

	// Верхняя полосочка(для отображения пустого заголовка передать ' ' - пробел)
	if(windowTitle != '')
	{
		var topbar = document.createElement("div");
		topbar.className = "topbar";
		windowDiv.insertBefore(topbar, windowDiv.childNodes[0]);
	}

	windowDiv.style.display = "none";

	// Закрыть
	var wclose_img = document.createElement("img");
	wclose_img.src = '/admin/images/wclose.gif';

	wclose_img.onclick = function() {HideWindow(windowId); };

	if(windowTitle != '')
	{
		topbar.appendChild(wclose_img);

		// Заголовок окна
		var textNode = document.createTextNode(windowTitle);
		topbar.appendChild(textNode);
	}
}

// Отображает/скрывает окно
function SlideWindow(windowId)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		return false;
	}
	if (windowDiv.style.display == "block")
	{
		HideWindow(windowId);
	}
	else
	{
		ShowWindow(windowId);
	}
}

var prev_window = 0;

function ShowWindow(windowId)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		return false;
	}

	if (prev_window && prev_window != windowId)
	{
		HideWindow(prev_window);
	}

	prev_window = windowId;

	// 0 - pageWidth, 1 - pageHeight, 2 - windowWidth, 3 - windowHeight
	var arrayPageSize = getPageSize();

	// 0 - scrOfX, 1 - scrOfY
	var arrayScrollXY = getScrollXY();

	// Отображаем до определения размеров div-а
	windowDiv.style.display = 'block';

	var clientHeight = windowDiv.clientHeight;
	windowDiv.style.top = ((arrayPageSize[3] - clientHeight) / 2 + arrayScrollXY[1]) + 'px';

	var clientWidth = windowDiv.clientWidth;
	windowDiv.style.left = ((arrayPageSize[2] - clientWidth) / 2 + arrayScrollXY[0]) + 'px';

	// получаем ширину выпадающего блока и устанавливаем её для верхней и нижней границы
	groupChildElements = windowDiv.children;

	if (groupChildElements != undefined)
	{
		for (i = 0; i < groupChildElements.length; i++)
		{
			if(groupChildElements[i].className == 'b' | groupChildElements[i].className == 't')
			{
				groupChildElements[i].style.width = windowDiv.clientWidth + 'px';
			}

			if(groupChildElements[i].className == 'r' | groupChildElements[i].className == 'l')
			{
				groupChildElements[i].style.height = windowDiv.clientHeight + 'px';
			}
		}
	}
}

function HideWindow(windowId)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		return false;
	}

	windowDiv.style.display = 'none';
}

function ShowAttentionWindow()
{
	if(document.forms["EditAddItem"].elements["shop_items_catalog_type"][0].checked)
	{
		res = confirm("ВНИМАНИЕ! Для данного товара указаны электронные товары, при изменении типа данного товара на \"Обычный\", электронные товары для данного товара будут УДАЛЕНЫ! Вы уверены что хотите сменить тип данного товара?");

		if(res)
		{
			document.forms["EditAddItem"].elements["shop_items_catalog_type"][0].checked = 1;
		}
		else
		{
			document.forms["EditAddItem"].elements["shop_items_catalog_type"][1].checked = 1;
		}
	}
}

// Функции для всплывающего блока
function copyright_position(copyright)
{
	var windowDiv = document.getElementById(copyright);
	windowDiv.style.top = 'auto';
	windowDiv.style.left = 'auto';
	windowDiv.style.bottom = 55 + 'px';
	windowDiv.style.right = 25 + 'px';
	clear_timeout_copiright();
}

function clear_timeout_copiright()
{
	clearTimeout(timeout_copiright);
}

function set_timeout_copyright()
{
	timeout_copiright = setTimeout(function(){HideWindow('copyright')}, 500);
}

function InsertText(obj_id, text)
{
	obj = document.getElementById(obj_id);

	obj.focus();

	if (typeof(obj.selectionStart) == "number")
	{
		var start = obj.selectionStart;
		var end = obj.selectionEnd;

		obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.textLength);
		obj.setSelectionRange(end, end);
	}
}


// Магазин
function doSetLocation(shop_country_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Возвращаем обычный курсор
			document.body.style.cursor = '';

			// Убираем затемнение.
			HideLoadingScreen();

			if (req.responseJS != undefined)
			{
				// Данные.
				if (req.responseJS.result != undefined)
				{
					oSelect = document.getElementById(location_select_id);

					// Очищаем select
					oSelect.options.length = 0;

					// Добавляем значение " ... "
					oSelect.options[oSelect.options.length] = new Option(" ... ", 0);

					for (var key in req.responseJS.result)
					{
						oSelect.options[oSelect.options.length] = new Option(req.responseJS.result[key], key);
					}

					// Устанавливаем города
					//doSetCity(oSelect.options[oSelect.selectedIndex].value);
					oCity = document.getElementById(city_select_id);
					oCity.options.length = 0;
					oCity.options[oCity.options.length] = new Option(" ... ", 0);

					oCityarea = document.getElementById(cityarea_select_id);
					oCityarea.options.length = 0;
					oCityarea.options[oCityarea.options.length] = new Option(" ... ", 0);
				}
			}
			return true;
		}
	}

	req.open('get', "/admin/shop/shop.php?action=get_location&shop_country_id="+shop_country_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}

function doSetCity(shop_location_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Возвращаем обычный курсор
			document.body.style.cursor = '';

			// Убираем затемнение.
			HideLoadingScreen();

			if (req.responseJS != undefined)
			{
				// Данные.
				if (req.responseJS.result != undefined)
				{
					oSelect = document.getElementById(city_select_id);

					// Очищаем select
					oSelect.options.length = 0;

					// Добавляем значение " ... "
					oSelect.options[oSelect.options.length] = new Option(" ... ", 0);

					for (var key in req.responseJS.result)
					{
						oSelect.options[oSelect.options.length] = new Option(req.responseJS.result[key], key);
					}

					// Устанавливаем районы
					//doSetCityArea(oSelect.options[oSelect.selectedIndex].value);

					oCityarea = document.getElementById(cityarea_select_id);
					oCityarea.options.length = 0;
					oCityarea.options[oCityarea.options.length] = new Option(" ... ", 0);
				}
			}
			return true;
		}
	}

	req.open('get', "/admin/shop/shop.php?action=get_city&shop_location_id="+shop_location_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}

function doSetCityArea(shop_city_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Возвращаем обычный курсор
			document.body.style.cursor = '';

			// Убираем затемнение.
			HideLoadingScreen();

			if (req.responseJS != undefined)
			{
				// Данные.
				if (req.responseJS.result != undefined)
				{
					oSelect = document.getElementById(cityarea_select_id);

					// Очищаем select
					oSelect.options.length = 0;

					// Добавляем значение " ... "
					oSelect.options[oSelect.options.length] = new Option(" ... ", 0);

					for (var key in req.responseJS.result)
					{
						oSelect.options[oSelect.options.length] = new Option(req.responseJS.result[key], key);
					}
				}
			}
			return true;
		}
	}

	req.open('get', "/admin/shop/shop.php?action=get_cityarea&shop_city_id="+shop_city_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}

// Загружает полуенные значения в список с Id = object_id
function doSetList(request_path, object_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Возвращаем обычный кур сор
			document.body.style.cursor = '';

			// Убираем затемнение.
			HideLoadingScreen();

			if (req.responseJS != undefined)
			{
				// Данные.
				if (req.responseJS.result != undefined)
				{
					oSelect = document.getElementById(object_id);

					// Очищаем select
					oSelect.options.length = 0;

					// Добавляем значение " ... "
					oSelect.options[oSelect.options.length] = new Option(" ... ", 0);

					for (var key in req.responseJS.result)
					{
						oSelect.options[oSelect.options.length] = new Option(req.responseJS.result[key], key);
					}
				}
			}
			return true;
		}
	}

	req.open('get', request_path, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}

/**
* Вставка стандартного ответа в поле текста сообщения
*/
function InsertTemplate(template_id, helpdesk_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Возвращаем обычный курсор
			document.body.style.cursor = '';

			// Убираем затемнение.
			HideLoadingScreen();

			if (req.responseJS != undefined)
			{
				// Данные.
				if (req.responseJS.text != undefined)
				{
					oMessageTextarea = document.getElementById('helpdesk_message_message');
					oMessageTextarea.value = req.responseJS.text + oMessageTextarea.value;
				}
			}
			return true;
		}
	}

	req.open('get', "/admin/helpdesk/helpdesk.php?action=insert_template&template_id="+template_id+"&helpdesk_id="+helpdesk_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}

/**
* Показ истории сообщений
* @param int helpdesk_ticket_id идентификатор тикета
*/
function ShowMessageHistory(helpdesk_ticket_id)
{
	var oWindowId = 'heldesk_m_history_'+helpdesk_ticket_id;

	if (document.getElementById(oWindowId) == undefined)
	{
		// Создаем окно
		CreateWindow(oWindowId, 'История переписки', '600px', '');

		var oWindow = document.getElementById(oWindowId);

		// <div id="subdiv">
		var ElementDiv = document.createElement("div");
		ElementDiv.setAttribute("id", "subdiv");
		var DivNode = oWindow.appendChild(ElementDiv);

		// Запрос backend-у
		var req = new JsHttpRequest();

		// Отображаем экран загрузки
		ShowLoadingScreen();

		req.onreadystatechange = function()
		{
			if (req.readyState == 4)
			{
				// Возвращаем обычный курсор
				document.body.style.cursor = '';

				// Убираем затемнение.
				HideLoadingScreen();

				if (req.responseJS != undefined)
				{
					// Данные.
					if (req.responseJS.result != undefined)
					{
						//oMessageTextarea = document.getElementById(oWindowId);
						DivNode.innerHTML = req.responseJS.result;
					}
				}
				return true;
			}
		}

		req.open('get', "/admin/helpdesk/helpdesk.php?action=get_message_history&helpdesk_ticket_id="+helpdesk_ticket_id, true);

		// Отсылаем данные в обработчик.
		req.send(null);

		// Курсор ставим на часики.
		document.body.style.cursor = "wait";
	}

	SlideWindow(oWindowId);
}

/**
* Показ истории сообщений
* @param int helpdesk_ticket_id идентификатор тикета
*/
function ShowMessage(helpdesk_message_id)
{
	var oWindowId = 'heldesk_message_'+helpdesk_message_id;

	if (document.getElementById(oWindowId) == undefined)
	{
		// Создаем окно
		CreateWindow(oWindowId, 'Сообщение', '600px', '');

		var oWindow = document.getElementById(oWindowId);

		// <div id="subdiv">
		var ElementDiv = document.createElement("div");
		ElementDiv.setAttribute("id", "subdiv");
		var DivNode = oWindow.appendChild(ElementDiv);

		// Запрос backend-у
		var req = new JsHttpRequest();

		// Отображаем экран загрузки
		ShowLoadingScreen();

		req.onreadystatechange = function()
		{
			if (req.readyState == 4)
			{
				// Возвращаем обычный курсор
				document.body.style.cursor = '';

				// Убираем затемнение.
				HideLoadingScreen();

				if (req.responseJS != undefined)
				{
					// Данные.
					if (req.responseJS.result != undefined)
					{
						//oMessageTextarea = document.getElementById(oWindowId);
						DivNode.innerHTML = req.responseJS.result;
					}
				}
				return true;
			}
		}

		req.open('get', "/admin/helpdesk/helpdesk.php?action=get_message&helpdesk_message_id="+helpdesk_message_id, true);

		// Отсылаем данные в обработчик.
		req.send(null);

		// Курсор ставим на часики.
		document.body.style.cursor = "wait";
	}

	SlideWindow(oWindowId);
}

/**
* Отправка формы helpdesk по Ctrl+Enter
* @param obj event объект события
* @param obj formObj объект формы
*/
function submitForm(event, formObj)
{
	if (((event.keyCode == 13) || (event.keyCode == 10)) && (event.ctrlKey == true) && (formObj.send_message))
	{
		if (confirm("Вы действительно хотите отправить сообщение?"))
		{
			formObj.send_message.click();
		}
	}
}

/**
* Показ окна со списком флагов тикетов
* int helpdesk_ticket_id Идентификатор тикета
*/
function TicketFlagChangeWindow(helpdesk_ticket_id)
{
	var oWindowId = 'heldesk_ticket_'+helpdesk_ticket_id+'_flag';

	if (document.getElementById(oWindowId) == undefined)
	{
		// Создаем окно
		CreateWindow(oWindowId, 'Флаг', '215px', '215px');

		var oWindow = document.getElementById(oWindowId);

		// <div id="subdiv">
		var ElementDiv = document.createElement("div");
		ElementDiv.setAttribute("id", "subdiv_small");
		var DivNode = oWindow.appendChild(ElementDiv);

		var ElementForm = document.createElement("form");
		ElementForm.setAttribute("id", "formFlag_"+helpdesk_ticket_id);
		var FormNode = ElementDiv.appendChild(ElementForm);

		// Запрос backend-у
		var req = new JsHttpRequest();

		// Отображаем экран загрузки
		ShowLoadingScreen();

		req.onreadystatechange = function()
		{
			if (req.readyState == 4)
			{
				// Возвращаем обычный курсор
				document.body.style.cursor = '';

				// Убираем затемнение.
				HideLoadingScreen();

				if (req.responseJS != undefined)
				{
					// Данные.
					if (req.responseJS.result != undefined)
					{
						//oMessageTextarea = document.getElementById(oWindowId);
						FormNode.innerHTML = req.responseJS.result;
					}
				}
				return true;
			}
		}

		req.open('get', "/admin/helpdesk/helpdesk.php?action=get_flags&helpdesk_ticket_id="+helpdesk_ticket_id, true);

		// Отсылаем данные в обработчик.
		req.send(null);

		// Курсор ставим на часики.
		document.body.style.cursor = "wait";
	}

	SlideWindow(oWindowId);
}

/**
* Применение флага к тикету
* str windowId Идентификатор окна
* int ticketId Идентификатр тикета
*/
function SetFlag(windowId, ticketId)
{
	cbItem = document.getElementById(windowId);

	if (cbItem)
	{
		flagId = GetRadioValue(cbItem.flag);

		if (flagId != null)
		{
			// Запрос backend-у
			var req = new JsHttpRequest();

			// Отображаем экран загрузки
			ShowLoadingScreen();

			req.onreadystatechange = function()
			{
				if (req.readyState == 4)
				{
					// Возвращаем обычный курсор
					document.body.style.cursor = '';

					// Убираем затемнение.
					HideLoadingScreen();

					if (req.responseJS != undefined)
					{
						// Данные.
						if (req.responseJS.result != undefined)
						{
							SlideWindow(prev_window);
							if (req.responseJS.result != 'null')
							{
								var oImg = document.getElementById('image_' + ticketId);
								oImg.src = req.responseJS.result;
								oImg.alt = req.responseJS.alt;
								oImg.title = req.responseJS.alt;
							}
						}
					}

					return true;
				}
			}

			req.open('get', "/admin/helpdesk/helpdesk.php?action=set_flag&helpdesk_ticket_id="+ticketId+"&helpdesk_ticket_flags_id="+flagId, true);

			// Отсылаем данные в обработчик.
			req.send(null);

			// Курсор ставим на часики.
			document.body.style.cursor = "wait";
		}
	}
}

/**
* Определение выбранного переключателя Radio-объекта
* str radioObject Имя Radio-группы
*/
function GetRadioValue(radioObject)
{
	var value = null;

	for (var i = 0; i < radioObject.length; i++)
	{
		if (radioObject[i].checked)
		{
			value = radioObject[i].value;
			break;
		}
	}

	return value;
}














		var pollOptionsSize = 0;
		function addOption(n)
		{
			if (n >= pollOptionsSize) pollOptionsSize = n;
			pollOptionsSize++;
			n = pollOptionsSize;


			html = '<input type="hidden" name="item[options][' + n + '][id]" value="0" id="pollOptions_' + n + '" />';


			html += '<div style="float: left; margin-top: 5px;" class="item_div">';
			html += '<span class="caption">Порядок</span>';
			html += '<input type="text" onblur="FieldCheck(this)" onkeyup="FieldCheck(this)" onkeydown="FieldCheck(this)" size="5" value="" name="item[options][' + n + '][order]"/>';
			html += '</div>';

			html += '<div style="float: left; margin-top: 5px;" class="item_div">';
			html += '<span class="caption">Новый вариант ответа</span>';
			html += '<input type="text" onblur="FieldCheck(this)" onkeyup="FieldCheck(this)" onkeydown="FieldCheck(this)" size="50" value="" name="item[options][' + n + '][name]"/>';
			html += '</div>';

			html += '<div style="float: left; margin-top: 5px;" class="item_div">';
			html += '<span class="caption">Количество</span>';
			html += '<input type="text" onblur="FieldCheck(this)" onkeyup="FieldCheck(this)" onkeydown="FieldCheck(this)" size="5" value="" name="item[options][' + n + '][votes]"/>';
			html += '</div>';

			html += '<div style="clear: both;"><br /></div>';


			document.getElementById('newOptions').innerHTML = document.getElementById('newOptions').innerHTML + html;
		}




