/**
 * HostCMS
 * 
 * @author Hostmake LLC, http://www.hostcms.ru/
 * @version 5.x
 */

(function($) {
	// Предварительная загрузка изображений
	var cache = [];
	
	$.extend({
	preLoadImages: function()
	{
		var args_len = arguments.length;

		for (var i = args_len; i--;)
		{
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
	});
  
	$.preLoadImages("/admin/images/shadow-b.png",
	"/admin/images/shadow-l.png",
	"/admin/images/shadow-lb.png",
	"/admin/images/shadow-lt.png",
	"/admin/images/shadow-r.png",
	"/admin/images/shadow-rb.png",
	"/admin/images/shadow-rt.png",
	"/admin/images/shadow-t.png",
	"/admin/images/ajax_loader.gif");

	// Тень для окна
	$.fn.extend({
		applyShadow: function()
		{
			return this.each(function(index, object){
				var obj = $(object);
				
				$('<div>').attr("class", 'tl').appendTo(obj);
		    	$('<div>').attr("class", 't')
		    	.height(15)
		    	.appendTo(obj);
		    	
		    	$('<div>').attr("class", 'tr').appendTo(obj);
		    	$('<div>').attr("class", 'l')
		    	.width(17)
		    	.appendTo(obj);
		    	
		    	$('<div>').attr("class", 'r')
		    	.width(17)
		    	.appendTo(obj);
		    	
		    	$('<div>').attr("class", 'bl').appendTo(obj);
		    	
		    	$('<div>').attr("class", 'b')
		    	.height(21)
		    	.appendTo(obj);
		    	
		    	$('<div>').attr("class", 'br').appendTo(obj);
			});
		}
	});
	
	$.extend({
		appendInput: function(WindowId, ObjectId, InputName, InputValue)
		{
			WindowId = getWindowId(WindowId);
			
			var obj = $('#'+WindowId+' #'+ObjectId);
			
			if (obj.length == 1
			&& obj.find("input[name='"+InputName+"']").length == 0)
			{
				$('#'+WindowId+' #'+ObjectId).append(
					$('<input>')
					.attr('type', 'hidden')
					.attr('name', InputName)
					.val(InputValue));
			}
		}
		});
})(jQuery)

function applyTooltip()
{
	$("acronym").tooltip({
		'tipClass': 'shadowed',
		'offset': [-30, 10],
		'position': 'left center',
		predelay: 500,
		effect: 'fade',
		layout: '<div id="tooltip"/>',
		slideOffset: 30,
		onBeforeShow: function(event, position)
		{
	    	var trigger = this.getTrigger();
	    	var obj = this.getTip();
			var conf = this.getConf();

			var triggerOuterWidth = trigger.outerWidth();
			
			var delta = (obj.outerWidth() + triggerOuterWidth) / 2 - triggerOuterWidth + 10;

			// Заменяем смещение, чтобы подсказка была от начала строки
			conf.offset = [conf.offset[0], delta];
    		
	    	// Оформление еще не было задано
			if (obj.find('.tl').size() == 0)
			{
				obj.applyShadow();

				// Tail
		    	$('<div>').attr("class", 'shadow_tail')
		    	.css('left', "3px")
		    	.css('bottom', "-30px")
		    	.css('width', "13px")
		    	.append($('<img>').attr("src", '/admin/images/shadow_tail.gif'))
		    	.appendTo(obj);
			}
	  	}
	});
}

$.ajaxSetup({
	cache: false,
	error: function(XMLHttpRequest, textStatus, errorThrown) {
			HideLoadingScreen();
			alert('Ajax error: ' + textStatus + ', ' + errorThrown);
		}
});

function formatTable(WindowId)
{
	WindowId = getWindowId(WindowId);
	
	$("#"+WindowId+" table.admin_table tr:not(.admin_table_title, .admin_table_filter):nth-child(odd)")
	.attr('class', 'row_table')
	.mouseover(function(){
		$(this).attr('class', 'row_table_over');
	})
	.mouseout(function(){
		$(this).attr('class', 'row_table');
	});
	
	$("#"+WindowId+" table.admin_table tr:not(.admin_table_title, .admin_table_filter):nth-child(even)").attr('class', 'row_table_odd')
	.mouseover(function(){
		$(this).attr('class', 'row_table_over_odd');
	})
	.mouseout(function(){
		$(this).attr('class', 'row_table_odd');
	});
}

function formatTextarea(WindowId)
{
	WindowId = getWindowId(WindowId);
	$('#'+WindowId+' textarea').elastic();
}

// Установка 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 + "=" + HostcmsEscape(value) +
	((expires) ? "; expires=" + date.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

	document.cookie = VarCookie;
}

// Кроссбраузерная функция получения размеров экрана,
// используется в функции ShowLoadingScreen.
function getPageSize()
{
	var xScroll, yScroll;

	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;
	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 ];
}

// Скрытие div-а
function HideObject(obj)
{
	obj.css('zoom', 1)
		.css('width', 0)
		.css('height', 0)
		.css('visibility', 'hidden')
		.css('overflow', 'hidden');
}

// Показ div-а
function ShowObject(obj)
{
	obj.css('zoom', 1)
		.css('width', 'auto')
		.css('height', 'auto')
		.css('visibility', 'visible')
		.css('overflow', 'visible');
}

// Показ закладок на странице администрирования
function ShowLayer(WindowId, AItemId, ASpan, FormID)
{
	WindowId = getWindowId(WindowId);
	
	// Получаем элемент формы
	var FormElement = $("#"+WindowId+" #"+FormID);
	
	if (FormElement.length > 0)
	{
		// div
		FormElement.find("div[id^='tab_page_'][id!='"+AItemId+"']").each(function(){
			HideObject($(this));
		});

		FormElement.find("div[id='"+AItemId+"']").each(function(){
			ShowObject($(this));
		});

		// li
		FormElement.find("li[id^='id_tab_span_'][id!='"+ASpan+"']").each(function(){
			$(this).attr('class', '');
		});

		FormElement.find("li[id='"+ASpan+"']").each(function(){
			$(this).attr('class', 'current_li');
		});
	}

	return true;
}

// =============================================
// Функции работы с меню
// =============================================
changeFontSizeTimer = new Array();
menuTimer = new Array();

function HostCMSMenuOver(CurrenElementId, LevelMenu, ChildId)
{
	clearTimeout(menuTimer[CurrenElementId]);
	
	CurrenElement = $("#"+CurrenElementId);

	if (CurrenElement.length > 0)
	{
		var jChild = $("#"+ChildId);

		// Оформление еще не было задано
		if (jChild.find('.tl').size() == 0)
		{
			jChild.applyShadow();
		}

		decor(CurrenElement, LevelMenu);
		
		jChild.css('display', 'block');
	}
}

function HostCMSMenuOut(CurrenElementId, LevelMenu, ChildId)
{
	menuTimer[CurrenElementId] = setTimeout(function(){
		CurrenElement = $("#"+CurrenElementId);

		if (CurrenElement.length > 0)
		{
			unDecor(CurrenElement, LevelMenu);
		
			var jChild = $("#"+ChildId);
			jChild.css('display', 'none');
		}
	}, 50);
}

// Функция визуального оформления элементов меню
function decor(CurrenElement, LevelMenu)
{
	if (LevelMenu == 1) // для первого уровня вложенности
	{
		CurrenElement
			.css('background-image', "url('/admin/images/line3.gif')")
			.css('background-repeat', 'repeat-x')
			.css('background-position', '0 100%');
		
		var child = CurrenElement.children;
		var CurrenElementId = CurrenElement.attr('id');
		
		if (changeFontSizeTimer[CurrenElementId] != '')
		{
			clearTimeout(changeFontSizeTimer[CurrenElementId]);
		}
		changeFontSize(CurrenElement.attr('id'), 1, 13);
	}
}

// Функция визуального оформления элементов меню
function unDecor(CurrenElement, LevelMenu)
{
	if (LevelMenu==1)
	{
		var CurrenElementId = CurrenElement.attr('id');
		
		clearTimeout(changeFontSizeTimer[CurrenElementId]);

		CurrenElement
			.css('background-image', "url('/admin/images/line1.gif')")
			.css('background-repeat', 'repeat-x')
			.css('background-position', '0 100%');
		
		changeFontSize(CurrenElement.attr('id'), -1, 10);
	}
}

// Функции оформления
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);
		}
	}
}

/**
 * Создание окна
 * 
 * @param windowId идентификатор окна
 * @param windowTitle заголовок окна
 * @param windowWidth ширина окна
 * @param windowHeight высота окна
 * @param type тип закрытия окна, 0 - скрыть, 1 - уничтожить
 */
function CreateWindow(windowId, windowTitle, windowWidth, windowHeight, typeClose)
{
	var removeWindow = (typeof typeClose != 'undefined' && typeClose == 1);
		
	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;
	}

	$(windowDiv).applyShadow();

	// Верхняя полосочка(для отображения пустого заголовка передать пробел)
	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';

	if (removeWindow)
	{
		wclose_img.onclick = function() { $("#"+windowId).remove(); };
	}
	else
	{
		wclose_img.onclick = function() {HideWindow(windowId); };
	}

	if(windowTitle != '')
	{
		topbar.appendChild(wclose_img);

		// Заголовок окна
		var textNode = document.createTextNode(windowTitle);
		topbar.appendChild(textNode);
	}
}

// Отображает/скрывает окно
function SlideWindow(windowId)
{
	if ($("#"+windowId).css("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;
	var clientWidth = windowDiv.clientWidth;
	
	// Если высота div-а больше высоты окна
	if (clientHeight > arrayPageSize[3])
	{
		// Положим высоту равной 90% высоты окна
		clientHeight = Math.round(arrayPageSize[3] * 0.9);
	}
	
	// Если ширина div-а больше ширины окна
	if (clientWidth > arrayPageSize[2])
	{
		// Положим ширину равной 90% высоты окна
		clientWidth = Math.round(arrayPageSize[2] * 0.9);
	}
	
	windowDiv.style.top = ((arrayPageSize[3] - clientHeight) / 2 + arrayScrollXY[1]) + 'px';
	windowDiv.style.left = ((arrayPageSize[2] - clientWidth) / 2 + arrayScrollXY[0]) + 'px';
}

function HideWindow(windowId)
{
	$("#"+windowId).css('display', 'none');
}

function ShowAttentionWindow()
{
	if(document.forms["EditAddItem"].elements["shop_items_catalog_type"][0].checked || document.forms["EditAddItem"].elements["shop_items_catalog_type"][2].checked)
	{
		res = confirm("ВНИМАНИЕ! Для данного товара указаны электронные товары, при изменении типа данного товара на \"Обычный\", электронные товары для данного товара будут УДАЛЕНЫ! Вы уверены что хотите сменить тип данного товара?");

		if(res && document.forms["EditAddItem"].elements["shop_items_catalog_type"][0].checked)
		{
			document.forms["EditAddItem"].elements["shop_items_catalog_type"][0].checked = 1;
		}
		else if(res && document.forms["EditAddItem"].elements["shop_items_catalog_type"][2].checked)
		{
			document.forms["EditAddItem"].elements["shop_items_catalog_type"][2].checked;
		}
		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)
		{
			// Убираем затемнение.
			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);
}

function doSetCity(shop_location_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Убираем затемнение.
			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);
}

function doSetCityArea(shop_city_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Убираем затемнение.
			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);
}

// Загружает полученные значения в список с Id = object_id
function doSetList(request_path, object_id)
{
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Убираем затемнение.
			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);
}

// Изменение статуса заказа товара
function ChangeOrderStatus()
{
	var date = new Date(), day = date.getDate(), month = date.getMonth() + 1, hours = date.getHours(), minutes = date.getMinutes();

	if (day < 10)
	{
		day = '0' + day;
	}

	if (month < 10)
	{
		month = '0' + month;
	}

	if (hours < 10)
	{
		hours = '0' + hours;
	}

	if (minutes < 10)
	{
		minutes = '0' + minutes;
	}

	document.getElementById('order_change_status_date_time_id').value = day + '.' + month + '.' + date.getFullYear() + ' ' + hours + ':' + minutes + ':' + '00';
}

/**
 * Вставка стандартного ответа в поле текста сообщения
 */
function InsertTemplate(WindowId, template_id, helpdesk_id)
{
	WindowId = getWindowId(WindowId);
	
	// Отображаем экран загрузки
	ShowLoadingScreen();
	
	var link = "/admin/helpdesk/helpdesk.php?action=insert_template&template_id="+template_id+"&helpdesk_id="+helpdesk_id;
	
	$.ajax({
		context: $("#"+WindowId), // станет контекстом (this)
		url: link,
		data: {'JsHttpRequest': Math.round(new Date().getTime() / 1000) + '-xml',
		'window_id': WindowId},
		dataType: 'json',
		success: function(data, status, XMLHttpRequest)
		{
			if (typeof data.js != 'undefined')
			{
				if (typeof data.js.text != 'undefined')
				{
					id_textarea = 'helpdesk_message_message';
					var jTextArea = $(this).find('#'+id_textarea);
					
					jTextArea.val(jTextArea.val() + data.js.text);
					
					// Работу с визуальным редактором ведём
					if (typeof tinyMCE != 'undefined')
					{
						if (tinyMCE.getInstanceById(id_textarea + '_ID') != null)
						{
							tinyMCE.getInstanceById(id_textarea + '_ID').setContent(data.js.text);
						}
					}
				}
			}

			// Убираем затемнение.
			HideLoadingScreen();
		}
	});
}

/**
 * Показ истории сообщений
 * 
 * @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', '', 1);

		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)
			{
				// Убираем затемнение.
				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);
	}

	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, 'Сообщение № ' + helpdesk_message_id, '600px', '', 1);

		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)
			{
				// Убираем затемнение.
				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);
	}

	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', 1);

		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)
			{
				// Убираем затемнение.
				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);
	}

	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)
				{
					// Убираем затемнение.
					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);
		}
	}
}

/**
 * Определение выбранного переключателя 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;
}

function SetControlElementsStatus(WindowId, ControlElementsStatus)
{
	WindowId = getWindowId(WindowId);
	
	$("#"+WindowId+" #ControlElements input").attr('disabled', !ControlElementsStatus);
}

function cSelectFilter(WindowId, sObjectId)
{
	this.WindowId = getWindowId(WindowId);
	this.sObjectId = sObjectId;
	
	// Игнорировать регистр
	this.ignoreCase = true;
	this.timeout = null;
	this.pattern = '';
	this.aOriginalOptions = null;
	this.sSelectedValue = '';
	
	// Сейчас происходит фильтрация
	this.is_filtering = false;
	
	// Установка требуемого шаблона фильтрации
	this.Set = function(pattern) {
		this.pattern = pattern;
		this.is_filtering = (pattern.length != 0);
	}

	// Указывает регулярному выражению игнорировать регистр
	this.SetIgnoreCase = function(value) {
		this.ignoreCase = value;
	}

	this.GetCurrentSelectObject = function() {
		this.oCurrentSelectObject = $("#"+this.WindowId+" #"+this.sObjectId);
	}
	
	this.Init = function() {

		this.GetCurrentSelectObject();
		
		if (this.oCurrentSelectObject.length == 1)
		{
			var jOptions = this.oCurrentSelectObject.find("option");

			if (jOptions.length > 0)
			{
				// Сохраняем установленное до фильтрации значение
				this.sSelectedValue = this.oCurrentSelectObject.find("option:selected").val();
				
				this.aOriginalOptions = new Array();

				var jOptionItem;

				for (var i = 0, count = jOptions.length; i < count; i++) {
					jOptionItem = $(jOptions.get(i));
					
					this.aOriginalOptions[i] = new Option(
							jOptionItem.text(),
							jOptionItem.text(), false);
			
					// Если есть значение, запишем его
					if (jOptionItem.val()) {
						this.aOriginalOptions[i].value = jOptionItem.val();
					}
				}
			}
		}
	}

	this.Filter = function() {
		// Если фильтрация - получаем объект
		if (this.is_filtering)
		{
			// Заново получаем объект, т.к. при AJAX-запросе на момент Init-а
			// объект мог не существовать
			this.GetCurrentSelectObject();
		}
		
		if (this.aOriginalOptions == null
		|| this.aOriginalOptions.length == 0)
		{
			this.Init();
		}

		if (this.oCurrentSelectObject.length == 1)
		{
			// Сбрасываем все значения списка
			this.oCurrentSelectObject.empty();
			
			if (this.ignoreCase) {
				var attributes = 'i';
			} else {
				var attributes = '';
			}
			
			var regexp = new RegExp(this.pattern, attributes);
			
			var iNewOptionsIndex = 0;

			for (var i = 0; i < this.aOriginalOptions.length; i++)
			{
				if (regexp.test(' ' + this.aOriginalOptions[i].text))
				{
					
					this.oCurrentSelectObject.append(
						$('<option>')
							.text(this.aOriginalOptions[i].text)
							.val(this.aOriginalOptions[i].value)
							.attr('selected', (this.aOriginalOptions[i].value == this.sSelectedValue))
					);
				}
			}
		}
	}
}

// --- [Menu] ---

var action = '';
var aHeights = new Array();

function SubMenu(divId)
{
	if (action == '')
	{
		var subDivHeight = $("div[id="+divId+"]").height();
		
		if ($("div[id="+divId+"]").height() == 0)
		{
			action = 'showing';
			ShowSubMenu(divId, aHeights[divId]);

			// Сохраняем состояние меню
			var reg = /id_(\d+)/;
			var arr = reg.exec(divId);

			// Отправляем информацию Backend-у
			sendRequest('/admin/index.php?show_sub_menu=' + arr[1], 'get');
		}
		else
		{
			aHeights[divId] = subDivHeight;
			action = 'hiding';

			HideSubMenu(divId);
			
			// Сохраняем состояние меню
			var reg = /id_(\d+)/;
			var arr = reg.exec(divId);

			// Отправляем информацию Backend-у
			sendRequest('/admin/index.php?hide_sub_menu=' + arr[1], 'get');
		}
	}
}

function ShowSubMenu (divId, maxHeight)
{
	$("div[id="+divId+"]").animate({
		height: maxHeight,
		opacity: 1.0}, {
		duration: 'normal',
		complete: function(){
			action = '';
		}
	});
}

function HideSubMenu(divId)
{
	$("div[id="+divId+"]").animate({
		height: 0,
		opacity: 0}, {
		duration: 'normal',
		complete: function(){
			action = '';
		}
	});
}

// -------------------------------------
function MainMenu(divId)
{
	if (action == '')
	{
		if ($("div[id="+divId+"]").width() == 0)
		{
			action = 'showing';
			ShowMainMenu(divId);
			
			// Отправляем информацию Backend-у, 0 - показали
			sendRequest('/admin/index.php?main_menu=0', 'get');
		}
		else
		{
			action = 'hiding';
			HideMainMenu(divId);
			
			// Отправляем информацию Backend-у, 1 - скрыли
			sendRequest('/admin/index.php?main_menu=1', 'get');
		}
	}
}

function ShowMainMenu(divId)
{
	var RightMaxWidth = 215;
	var RightPadding = 30;
	
	$("div[id=body_left_box]")
	.css('border-right-style', "solid")
	.css('border-right-color', "white");
	
	$("div[id=body_left_box]")
	.css('margin-right', -1 * RightMaxWidth)
	.css('border-right-width', RightMaxWidth);

	$("div[id=body]")
	// Начинаем с 30, чтобы у IE не было горизонтальной полоски
	.css('padding-right', RightPadding)
	.animate({
		paddingRight: RightMaxWidth + RightPadding
		}, {
		queue: false,
		duration: 'normal',
		complete: function(){
			$(this).css('padding-right', '');
		}
	});

	$("div[id="+divId+"]")
	.css('display', 'block')
	.animate({
		width: RightMaxWidth,
		opacity: 1.0}, {
		duration: 'normal',
		complete: function(){
			action = '';
			$("img[id=MainMenuImg]").attr('src', '/admin/images/menu_show.gif');
		}
	});
}

function HideMainMenu(divId)
{
	var RightPadding = 30;

	$("div[id=body]")
	.animate({
		paddingRight: RightPadding
		}, {
		queue: false,
		duration: 'normal',
		complete: function(){
		}
	});
	
	$("div[id="+divId+"]")
	.animate({
		width: 0,
		opacity: 0}, {
		duration: 'normal',
		complete: function(){
			action = '';
			$(this).css('display', 'none');
			// Убираем оставшиеся 30 пикселей после скрытия самого блока
			$("div[id=body]").css('padding-right', 0);
			$("img[id=MainMenuImg]").attr('src', '/admin/images/menu_show_reverse.gif');
			
			$("div[id=body_left_box]")
			.css('margin-right', -1 * RightPadding)
			.css('border-right-width', 0);
		}
	});
}

// --- / [Menu] ---


/**
 * Модуль "Структура сайта"
 * 
 * @WindowId
 * @ASelectedItem код выбранного элемента
 * @structure_id идентификатор структуры
 * @lib_dir_id раздел типовых динамически страниц
 * @lib_id идентификатор типовых динамически страниц
 */
function SetViewStructure(WindowId, ASelectedItem, iStructureId, iLibDirId, iLibId)
{
	WindowId = getWindowId(WindowId);
	
	var templates_id = "none",
		documents_dir_list_id = "none",
		documents_list_id = "none",
		documents_list_image_id = "none",
		structure_external_link_id = "none",
		lib_dir_id = "none",
		lib_id = "none",
		lib_properties = "none";
	
	switch (ASelectedItem)
	{
		default:
		case 0: // Страница
			documents_dir_list_id = "block";
			documents_list_id = "block";
			documents_list_image_id = "block";
			structure_external_link_id = "block";
			HideObject($("#"+WindowId+" #module_id"));
			HideObject($("#"+WindowId+" #module_config_id"));
		break;

		case 1: // Динамическая страница
			templates_id = "block";
			// Для CodePress показываем таким образом
			ShowObject($("#"+WindowId+" #module_id"));
			ShowObject($("#"+WindowId+" #module_config_id"));
		break;
		
		case 2: // Типовая дин. страница
			templates_id = "block";
			lib_dir_id = "block";
			lib_id = "block";
			lib_properties = "block";
			HideObject($("#"+WindowId+" #module_id"));
			HideObject($("#"+WindowId+" #module_config_id"));
			
			// Загружаем список типовых страниц.
			DoLoadLibs(iLibDirId, iLibId);
	
			// Получаем свойства для выбранной типовой динамической страницы.
			DoLoadLibProperties(iLibId, iStructureId);
		break;
	}
	
	$("#"+WindowId+" #templates_id").css('display', templates_id);
	$("#"+WindowId+" #documents_dir_list_id").css('display', documents_dir_list_id);
	$("#"+WindowId+" #documents_list_id").css('display', documents_list_id);
	$("#"+WindowId+" #documents_list_image_id").css('display', documents_list_image_id);
	$("#"+WindowId+" #structure_external_link_id").css('display', structure_external_link_id);
	$("#"+WindowId+" #lib_dir_id").css('display', lib_dir_id);
	$("#"+WindowId+" #lib_id").css('display', lib_id);
	$("#"+WindowId+" #lib_properties").css('display', lib_properties);
}

function ShowRows(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	var structure_propertys_define_value = 'none',
		structure_propertys_lists_id = 'none',
		structure_propertys_information_systems_id = 'none',
		default_date_value_id = 'none',
		default_datetime_value_id = 'none',
		default_checked_value_id = 'none';

	index = parseInt(index);
							
	switch (index)
	{
		case 0: // Число
		case 1: // Строка
		case 4: // Большое текстовое поле
		case 6: // Визуальный редактор
		{
			structure_propertys_define_value = 'block';
			break;
		}
		case 2: // Файл
		{
			break;
		}
		case 3: // Список
		{
			structure_propertys_lists_id = 'block';
			break;
		}
		case 5: // Информационная система
		{
			structure_propertys_information_systems_id = 'block';
			break;
		}
		case 7: // Флажок
		{
			default_checked_value_id = 'block';
			break;
		}
		case 8: // Дата
		{
			default_date_value_id = 'block';
			break;
		}
		case 9: // ДатаВремя
		{
			default_datetime_value_id = 'block';
			break;
		}
	}
	
	$("#"+WindowId+" #structure_propertys_define_value").css('display', structure_propertys_define_value);
	$("#"+WindowId+" #structure_propertys_lists_id").css('display', structure_propertys_lists_id);
	$("#"+WindowId+" #structure_propertys_information_systems_id").css('display', structure_propertys_information_systems_id);
	$("#"+WindowId+" #default_date_value_id").css('display', default_date_value_id);
	$("#"+WindowId+" #default_datetime_value_id").css('display', default_datetime_value_id);
	$("#"+WindowId+" #default_checked_value_id").css('display', default_checked_value_id);
}

function ShowRowsAdminForm(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);
	
	var list_image_path_id = 'none',
		list_values_id = 'none',
		link_id = 'none',
		onclick_id = 'none';
	
	switch (index)
	{
		case 1: // Текст
		case 4: // Ссылка
		case 5: // Дата-время
		case 6: // Дата
		case 9: // Текст AS IS
		case 10: // Вычисляемое поле
		{
			link_id = 'block';
			onclick_id = 'block';
			break;
		}
		case 7: // Картинка-ссылка
		{
			list_image_path_id = 'block';
			link_id = 'block';
			onclick_id = 'block';
			break;
		}
		case 8: // Список
		{
			list_values_id = 'block';
			link_id = 'block';
			onclick_id = 'block';
			break;
		}
	}
	
	$("#"+WindowId+" #list_image_path_id").css('display', list_image_path_id);
	$("#"+WindowId+" #list_values_id").css('display', list_values_id);
	$("#"+WindowId+" #link_id").css('display', link_id);
	$("#"+WindowId+" #onclick_id").css('display', onclick_id);
}

function ShowRowsBannerControl(WindowId, index)
{
	WindowId = getWindowId(WindowId);
	
	index = parseInt(index);

	var advertisement_banner_swf_path = 'none',
		advertisement_banner_image_path = 'none',
		advertisement_banner_image_link = 'none',
		advertisement_banner_structure_id = 'none',
		advertisement_banner_text = 'none';

	switch (index)
	{
		case 0: // Изображение
		{
			advertisement_banner_image_path = 'block';
			advertisement_banner_image_link = 'block';
			break;
		}
						
		case 1: // html
		{
			advertisement_banner_text = 'block';
			break;
		}
		
		case 2: // Всплывающий
		{
			advertisement_banner_structure_id = 'block';
			break;
		}
		
		case 3: // Флэш
		{
			advertisement_banner_swf_path = 'block';
			advertisement_banner_image_link = 'block';
			break;
		}
	}
	
	$("#"+WindowId+" #advertisement_banner_swf_path").css('display', advertisement_banner_swf_path);
	$("#"+WindowId+" #advertisement_banner_image_path").css('display', advertisement_banner_image_path);
	$("#"+WindowId+" #advertisement_banner_image_link").css('display', advertisement_banner_image_link);
	$("#"+WindowId+" #advertisement_banner_structure_id").css('display', advertisement_banner_structure_id);
	$("#"+WindowId+" #advertisement_banner_text").css('display', advertisement_banner_text);
}

function ShowRowsForms(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);
	
	var list_id = 'none',
		cols_id = 'none',
		rows_id = 'none',
		checked_id = 'none',
		size_id = 'none',
		default_value_id = 'none',
		obligatory_id = 'none';
	
	switch (index)
	{
	 	case 0: // Поле ввода.
	 	default:
	 		size_id = 'block';
	 		default_value_id = 'block';
	 		obligatory_id = 'block';
			break;
		 case 1: // Пароль.
			size_id = 'block';
	 		default_value_id = 'block';
	 		obligatory_id = 'block';
		 	break;
		 case 2: // Поле загрузки файла.	 	
			size_id = 'block';
			obligatory_id = 'block';
			break;
		 case 3: // Переключатель.
			list_id = 'block';
			obligatory_id = 'block';
		 	break;
		 case 4: // Флажок.
			checked_id = 'block';
			obligatory_id = 'block';
			break;
		 case 5: // Большое текстовое поле.
			cols_id = 'block';
			rows_id = 'block';
			default_value_id = 'block';
			obligatory_id = 'block';
			break;
		 case 6: // Список.
			list_id = 'block';
			obligatory_id = 'block';
			break;
 		case 7: // Скрытое поле.
			default_value_id = 'block';
			obligatory_id = 'block';
			break;
		 case 8: // Надпись.
			default_value_id = 'block';
			obligatory_id = 'block';
			break;
		case 9: // Список флажков
			list_id = 'block';
			obligatory_id = 'block';
			break;
	}
	$("#"+WindowId+" #list_id").css('display', list_id);
	$("#"+WindowId+" #cols_id").css('display', cols_id);
	$("#"+WindowId+" #rows_id").css('display', rows_id);
	$("#"+WindowId+" #checked_id").css('display', checked_id);
	$("#"+WindowId+" #size_id").css('display', size_id);
	$("#"+WindowId+" #default_value_id").css('display', default_value_id);
	$("#"+WindowId+" #obligatory_id").css('display', obligatory_id);
}

function ShowRowsGroupPropertys(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);

	var list_id = 'none',
		default_value_id = 'none',
		default_date_value_id = 'none',
		default_datetime_value_id = 'none',
		information_system_id = 'none',
		default_checked_value_id = 'none',
		information_propertys_groups_big_width = 'none',
		information_propertys_groups_big_height = 'none',
		information_propertys_groups_small_width = 'none',
		information_propertys_groups_small_height = 'none';

	switch (index)
	{
		case 0: // Число
		case 1: // Строка
		case 4: // Большое текстовое поле
		case 5: // Визуальный редактор
		default:
		{
			default_value_id = 'block';
			break;
		}
		case 2: // Файл
		{
			information_propertys_groups_big_width = 'block';
			information_propertys_groups_big_height = 'block';
			information_propertys_groups_small_width = 'block';
			information_propertys_groups_small_height = 'block';
			break;
		}
		case 3: // Список
		{
			list_id = 'block';
			break;
		}
		case 6: // Информационная система
		{
			information_system_id = 'block';
			break;
		}
		case 7: // Флажок
		{
			default_checked_value_id = 'block';
			break;
		}
		case 8: // Дата
		{
			default_date_value_id = 'block';
			break;
		}
		case 9: // Дата-время
		{
			default_datetime_value_id = 'block';
			break;
		}
	}
	
	$("#"+WindowId+" #list_id").css('display', list_id);
	$("#"+WindowId+" #default_value_id").css('display', default_value_id);
	$("#"+WindowId+" #default_date_value_id").css('display', default_date_value_id);
	$("#"+WindowId+" #default_datetime_value_id").css('display', default_datetime_value_id);
	$("#"+WindowId+" #information_system_id").css('display', information_system_id);
	$("#"+WindowId+" #default_checked_value_id").css('display', default_checked_value_id);
	$("#"+WindowId+" #information_propertys_groups_big_width").css('display', information_propertys_groups_big_width);
	$("#"+WindowId+" #information_propertys_groups_big_height").css('display', information_propertys_groups_big_height);
	$("#"+WindowId+" #information_propertys_groups_small_width").css('display', information_propertys_groups_small_width);
	$("#"+WindowId+" #information_propertys_groups_small_height").css('display', information_propertys_groups_small_height);
}

function ShowRowsItemPropertys(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);
	
	var list_id = 'none',
		default_value_id = 'none',
		default_date_value_id = 'none',
		default_datetime_value_id = 'none',
		information_system_id = 'none',
		default_checked_value_id = 'none',
		information_propertys_default_big_width = 'none',
		information_propertys_default_small_width = 'none',
		information_propertys_default_big_height = 'none',
		information_propertys_default_small_height = 'none';

	switch (index)
	{
		case 0: // Число
		case 1: // Строка
		case 4: // Большое текстовое поле
		case 6: // Визуальный редактор
		default:
		{
			default_value_id = 'block';
			break;
		}
		case 2: // Файл
		{
			information_propertys_default_big_width = 'block';
			information_propertys_default_small_width = 'block';
			information_propertys_default_big_height = 'block';
			information_propertys_default_small_height = 'block';
			break;
		}
		case 3: // Список
		{
			list_id = 'block';
			break;
		}
		case 5: // Информационная система
		{
			information_system_id = 'block';
			break;
		}
		case 7: // Флажок
		{
			default_checked_value_id = 'block';
			break;
		}
		case 8: // Дата
		{
			default_date_value_id = 'block';
			break;
		}
		case 9: // Дата-время
		{
			default_datetime_value_id = 'block';
			break;
		}
	}
	$("#"+WindowId+" #list_id").css('display', list_id);
	$("#"+WindowId+" #default_value_id").css('display', default_value_id);
	$("#"+WindowId+" #default_date_value_id").css('display', default_date_value_id);
	$("#"+WindowId+" #default_datetime_value_id").css('display', default_datetime_value_id);
	$("#"+WindowId+" #information_system_id").css('display', information_system_id);
	$("#"+WindowId+" #default_checked_value_id").css('display', default_checked_value_id);
	$("#"+WindowId+" #information_propertys_default_big_width").css('display', information_propertys_default_small_height);
	$("#"+WindowId+" #information_propertys_default_small_width").css('display', information_propertys_default_small_width);
	$("#"+WindowId+" #information_propertys_default_big_height").css('display', information_propertys_default_big_height);
	$("#"+WindowId+" #information_propertys_default_small_height").css('display', information_propertys_default_small_height);
}

function ShowRowsShopItemPropertysType(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);
	
	var list_of_properties_default_id = 'none',
		list_of_properties_mesures_id = 'none',
		list_of_properties_lists_id = 'none',
		checkbox = 'none',
		date_without_time = 'none',
		date_with_time = 'none',
		shop_list_of_properties_default_big_width = 'none',
		shop_list_of_properties_default_big_height = 'none',
		shop_list_of_properties_default_small_width = 'none',
		shop_list_of_properties_default_small_height = 'none';

	switch (index)
	{
		case 0: // Строка
		case 3: // Большое текстовое поле
		case 4: // Визуальный редактор
		default:
		{
			list_of_properties_default_id = 'block';
			list_of_properties_mesures_id = 'block';
			break;
		}
		case 1: // Файл
		{
			shop_list_of_properties_default_big_width = 'block',
			shop_list_of_properties_default_big_height = 'block',
			shop_list_of_properties_default_small_width = 'block',
			shop_list_of_properties_default_small_height = 'block';
			break;
		}
		case 2: // Список
		{
			list_of_properties_lists_id = 'block';
			break;
		}
		case 5: // Дата
		{
			date_without_time = 'block';
			break;
		}
		case 6: // ДатаВремя
		{
			date_with_time = 'block';
			break;
		}
		case 7: // Флажок
		{
			checkbox = 'block';
			break;
		}
	}
	$("#"+WindowId+" #list_of_properties_default_id").css('display', list_of_properties_default_id);
	$("#"+WindowId+" #list_of_properties_mesures_id").css('display', list_of_properties_mesures_id);
	$("#"+WindowId+" #list_of_properties_lists_id").css('display', list_of_properties_lists_id);
	$("#"+WindowId+" #checkbox").css('display', checkbox);
	$("#"+WindowId+" #date_without_time").css('display', date_without_time);
	$("#"+WindowId+" #date_with_time").css('display', date_with_time);
	$("#"+WindowId+" #shop_list_of_properties_default_big_width").css('display', shop_list_of_properties_default_big_width);
	$("#"+WindowId+" #shop_list_of_properties_default_big_height").css('display', shop_list_of_properties_default_big_height);
	$("#"+WindowId+" #shop_list_of_properties_default_small_width").css('display', shop_list_of_properties_default_small_width);
	$("#"+WindowId+" #shop_list_of_properties_default_small_height").css('display', shop_list_of_properties_default_small_height);
}


function ShowRowsShopGroupPropertysType(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	index = parseInt(index);
	
	var list_of_properties_default_id = 'none',
		list_of_properties_mesures_id = 'none',
		list_of_properties_lists_id = 'none',
		checkbox = 'none',
		date_without_time = 'none',
		date_with_time = 'none',
		shop_properties_group_default_big_width = 'none',
		shop_properties_group_default_big_height = 'none',
		shop_properties_group_default_small_width = 'none',
		shop_properties_group_default_small_height = 'none';
				
	switch (index)
	{
		case 0: // Строка
		case 3: // Большое текстовое поле
		case 4: // Визуальный редактор
		default:
		{
			list_of_properties_default_id = 'block';
			list_of_properties_mesures_id = 'block';
			break;
		}
		case 1: // Список - файл
		{
			shop_properties_group_default_big_width = 'block',
			shop_properties_group_default_big_height = 'block',
			shop_properties_group_default_small_width = 'block',
			shop_properties_group_default_small_height = 'block';
			break;
		}
		case 2: // Список
		{
			list_of_properties_lists_id = 'block';
			break;
		}
		case 5: // Дата
		{
			date_without_time = 'block';
			break;
		}
		case 6: // ДатаВремя
		{
			date_with_time = 'block';
			break;
		}
		case 7: // Флажок
		{
			checkbox = 'block';
			break;
		}
	}
	$("#"+WindowId+" #list_of_properties_default_id").css('display', list_of_properties_default_id);
	$("#"+WindowId+" #list_of_properties_mesures_id").css('display', list_of_properties_mesures_id);
	$("#"+WindowId+" #list_of_properties_lists_id").css('display', list_of_properties_lists_id);
	$("#"+WindowId+" #checkbox").css('display', checkbox);
	$("#"+WindowId+" #date_without_time").css('display', date_without_time);
	$("#"+WindowId+" #date_with_time").css('display', date_with_time);
	$("#"+WindowId+" #shop_properties_group_default_big_width").css('display', shop_properties_group_default_big_width);
	$("#"+WindowId+" #shop_properties_group_default_big_height").css('display', shop_properties_group_default_big_height);
	$("#"+WindowId+" #shop_properties_group_default_small_width").css('display', shop_properties_group_default_small_width);
	$("#"+WindowId+" #shop_properties_group_default_small_height").css('display', shop_properties_group_default_small_height);
}

function ShowRowsSiteUsers(WindowId, index)
{
	WindowId = getWindowId(WindowId);

	var list_id = 'none',
		rows_textarea_id = 'none',
		cols_textarea_id = 'none',
		checked_id = 'none',
		input_size_id = 'none',
		default_value_id = 'none';
	
	switch (index)
	{
		case 'text': // Текстовое поле
		{
			input_size_id = 'block';
			default_value_id = 'block';
			break;
		}
		case 'password': // Поле пароля
		case 'file': // Поле загрузки файла
		{
			input_size_id = 'block';
			break;
		}
		case 'radio': // Радиогруппа
		case 'select': // Список
		{
			list_id = 'block';
			break;
		}
		case 'checkbox': // Флажок 
		{
			 checked_id = 'block';
			 break;
		}
		case 'textarea': // Большое текстовое поле
		{
			rows_textarea_id = 'block';
			cols_textarea_id = 'block';
			default_value_id = 'block';
			break;
		}
		case 'hidden': // Скрытое поле
		{
			default_value_id = 'block';
			break;
		}
	}
	$("#"+WindowId+" #list_id").css('display', list_id);
	$("#"+WindowId+" #rows_textarea_id").css('display', rows_textarea_id);
	$("#"+WindowId+" #cols_textarea_id").css('display', cols_textarea_id);
	$("#"+WindowId+" #checked_id").css('display', checked_id);
	$("#"+WindowId+" #input_size_id").css('display', input_size_id);
	$("#"+WindowId+" #default_value_id").css('display', default_value_id);
}
