(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("/hostcmsfiles/images/shadow-b.png",
	"/hostcmsfiles/images/shadow-l.png",
	"/hostcmsfiles/images/shadow-lb.png",
	"/hostcmsfiles/images/shadow-lt.png",
	"/hostcmsfiles/images/shadow-r.png",
	"/hostcmsfiles/images/shadow-rb.png",
	"/hostcmsfiles/images/shadow-rt.png",
	"/hostcmsfiles/images/shadow-t.png",
	"/hostcmsfiles/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);
			});
		}
	});
	
})(jQuery)

function set_count_mod(input_id, step)
{
	var oCountMod = document.getElementById(input_id);
	
	if (!(iCurrCount = parseInt(oCountMod.value))) {
		iCurrCount = 0;
	}
	
	if (!(iCurrCount <= 0 && step < 0)) {
			oCountMod.value = iCurrCount + step;
	}
}

// Отображает/скрывает окно
function SlideWindow(windowId)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		return false;
	}

	if (windowDiv.style.display == "block")
	{
		HideWindow(windowId);
	}
	else
	{
		ShowWindow(windowId);
	}
}

// Удаляет дочерние элементы элемента с ID, равным node_id
function deleteChildNodes(node_id)
{
	var node = document.getElementById(node_id);

	if (node !== undefined)
	{
		if (node.hasChildNodes())
		{
			while (node.firstChild)
			{
				node.removeChild(node.firstChild);
			}
		}
	}
}

// Магазин
function doSetLocation(shop_country_id, path)
{
	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', path + "?action=get_location&shop_country_id="+shop_country_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);
}

function doSetCity(shop_location_id, path)
{
	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', path + "?action=get_city&shop_location_id="+shop_location_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);
}

function doSetCityArea(shop_city_id, path)
{
	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', path + "?action=get_cityarea&shop_city_id="+shop_city_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);
}

// Плавающие блоки
// получаем исходную позицию плавающего блока
function GetStyle(drag_object, axis)
{
	var str_value = "";

	if(document.defaultView && document.defaultView.getComputedStyle)
	{
		var css = document.defaultView.getComputedStyle(drag_object, null);
		str_value = css ? css.getPropertyValue(axis) : null;
	}
	else if(drag_object.currentStyle)
	{
		str_value = drag_object.currentStyle[axis];

		if (str_value == 'auto')
		{
			if (axis == 'top')
			{
				str_value = drag_object.offsetTop;
			}
			else
			{
				str_value = drag_object.offsetLeft;
			}
		}
	}

	return str_value;
}

function Draggable(drag_object)
{
	var xDelta = 0,
	yDelta = 0,
	xStart = 0,
	yStart = 0;

	// остановить событие
	function EndDrag()
	{
		document.onmouseup = null;
		document.onmousemove = null;
	}

	// считаем новую позицию при перетаскивании
	function Drag(drag_event)
	{
		drag_event = drag_event || window.event;

		xDelta = xStart - parseInt(drag_event.clientX);
		yDelta = yStart - parseInt(drag_event.clientY);

		xStart = parseInt(drag_event.clientX);
		yStart = parseInt(drag_event.clientY);

		drag_object.style.top = (parseInt(drag_object.style.top) - yDelta) + 'px';
		drag_object.style.left = (parseInt(drag_object.style.left) - xDelta) + 'px';
	}

	// начать перетаскивание
	function StartDrag(drag_event)
	{
		drag_event = drag_event || window.event;

		xStart = parseInt(drag_event.clientX);
		yStart = parseInt(drag_event.clientY);

		drag_object.style.top = parseInt(GetStyle(drag_object, 'top')) + 'px';
		drag_object.style.left = parseInt(GetStyle(drag_object, 'left')) + 'px';

		document.onmouseup = EndDrag;
		document.onmousemove = Drag;

		return false;
	}

	// связываем объект с событием
	drag_object.onmousedown = StartDrag;
}

function SetGradeMessage(message_id, grade_val)
{
	// Запрос backend-у
	var req = new JsHttpRequest();

	// Отображаем экран загрузки
	ShowLoadingScreen();

	req.onreadystatechange = function()
	{
		if (req.readyState == 4)
		{
			// Убираем затемнение.
			HideLoadingScreen();

			return true;
		}
	}

	req.open('get', "./?action=set_message_grade&helpdesk_message_id="+message_id+"&grade="+grade_val, true);

	// Отсылаем данные в обработчик.
	req.send(null);
}

/**
 * Обновление картинки CAPTCHA
 * captchaKey - идентификатор CAPTCHA
 * captchaHeight - высота картинки с CAPTCHA
 */
function ReNewCaptcha(captchaKey, captchaHeight)
{	
	if (document.images['captcha'] != undefined)
	{
		var antiCache = Math.floor(Math.random()*100000);
		document.images['captcha'].src = "/captcha.php?get_captcha=" + captchaKey + "&height=" + captchaHeight + "&anc=" + antiCache;
	}
}

/**
 * Обновление картинки CAPTCHA для картинки по ее ID
 * captchaKey - идентификатор CAPTCHA
 * captchaHeight - высота картинки с CAPTCHA
 */
function ReNewCaptchaById(imageId, captchaKey, captchaHeight)
{	
	// Пытаемся получить скрытый объект для input-а
	var captchaObject = document.getElementById(imageId);

	// Элемента нет, добавим его
	if (null != captchaObject && undefined !== captchaObject)
	{
		var antiCache = Math.floor(Math.random()*100000);
		captchaObject.src = "/captcha.php?get_captcha=" + captchaKey + "&height=" + captchaHeight + "&anc=" + antiCache;
	}
}

// Отображает/скрывает блок
function ShowHide(divId)
{
	var windowDiv = document.getElementById(divId);

	if (windowDiv == undefined)
	{
		return false;
	}

	if (windowDiv.style.display == "block")
	{
		windowDiv.style.display = 'none';
	}
	else
	{
		windowDiv.style.display = 'block';
	}
}

//Функция обратного вызова при загрузке формы добавления на доску объявлений
function callbackfunction_showFormAddItem(responseJS)
{
	if (typeof responseJS != 'undefined')
	{
		HideLoadingScreen();
	
		// Данные.
		if (typeof responseJS.result != 'undefined')
		{
			html = responseJS.result;

			document.getElementById('AddItemForm').innerHTML = html;

			// Выполняем скрипты из полученного с сервера HTML-а
			runScripts(document.getElementById('AddItemForm').getElementsByTagName('SCRIPT'));
			
			// Очищаем поле сообщений
			var div_id_message = document.getElementById('AddItemMessage');

			if (div_id_message)
			{
				div_id_message.innerHTML = '';
			}
			
			//cr('AddItemForm');
		}
	}
}

//Функция обратного вызова при отправке добавления на доску объявлений
function callbackfunction_SendFormItem(responseJS)
{
	if (typeof responseJS != 'undefined')
	{
		if (responseJS.message != 'undefined')
		{
			var div_id_message = document.getElementById('AddItemMessage');

			if (div_id_message)
			{
				div_id_message.innerHTML = responseJS.message;
				
				// Выполняем скрипты из полученного с сервера HTML-а
				runScripts(div_id_message.getElementsByTagName('SCRIPT'));
				
				// Переходим к сообщению
				window.location.href = (window.location.href.indexOf('#') >= 0 ? window.location.href : window.location.href + '#FocusAddItemMessage');
			}
		}
	}
}

function ShowImgWindow(title, src, width, height)
{
	obj = window.open("", "", "scrollbars=0,dialog=0,minimizable=1,modal=1,width="+width+",height="+height+",resizable=0");
	obj.document.write("<html>");
	obj.document.write("<head>");
	obj.document.write("<title>"+title+"</title>");
	obj.document.write("</head>");
	obj.document.write("<body topmargin=0 leftmargin=0 marginwidth=0 marginheight=0>");
	obj.document.write("<img src=\""+src+"\" width=\""+width+"\" height=\""+height+"\" />");
	obj.document.write("</body>");
	obj.document.write("</html>");
	obj.document.close();
}

function getElementsByName_iefix(tag, name) 
{
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();

	var iarr = 0;
	
	for(i = 0; i < elem.length; i++)
	{
		att = elem[i].getAttribute("name");

		if(att == name)
		{
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}

// Изменение высоты блока
function changeHeightFloatBlockBorder (oBorder, iHeightAttribute, iStyleTop)
{
	var iElementHeight = 0;
	
	for (i = 0; i < oBorder.length; i++)
	{
		iElementHeight = oBorder[i].parentNode.offsetHeight + iHeightAttribute;

		if (iElementHeight > 0)
		{
			oBorder[i].style.height = iElementHeight + 'px';
			oBorder[i].style.top = iStyleTop + 'px';
		}
	}
}
