﻿function callbackfunction_AddIntoCart(responseJS)
{
	sended_request = false;

	if (typeof responseJS != 'undefined')
	{
		if (typeof responseJS.cart != 'undefined')
		{
			html = responseJS.cart;

			var little_cart = document.getElementById('little_cart');
			
			if (little_cart)
			{
				little_cart.innerHTML = html;
			}

			var add_cart = document.getElementById('add_cart');
			
			if (add_cart)
			{
				add_cart.innerHTML = '<p class="added"><i>Товар добавлен в <a href="/cart/?reload">корзину</a>.</i></p>';
			}

			var link_cart = document.getElementById('link_cart');
			
			if (link_cart)
			{
				link_cart.innerHTML = '<span class="highlight">»</span>&nbsp;<a href="/cart/?reload">Заказать</a></div>';
			}
		}
	}
}

function AddIntoCart(shop_path, item_id, item_count)
{
	//location.href = shop_path + 'cart/?ajax_add_item_id=' + item_id + '&count=' + item_count;
	cmsrequest = shop_path + 'cart/?ajax_add_item_id=' + item_id + '&count=' + item_count;
	
	// Отправляем запрос backend-у
	sendRequest(cmsrequest, 'get', callbackfunction_AddIntoCart);
	
	return false;
}


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 ];
}

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 = '/hostcmsfiles/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;
	}

	// Добавлено  && windowId.indexOf('edit_window_') == 0 для того, чтобы при отображении всплывающего окошка с настройками изображения не закрывалось всплывающее окно ЦА
	if (prev_window && prev_window != windowId && (windowId.indexOf('edit_window_') == 0 || prev_window.indexOf('edit_window_') !== 0))
	{
		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';
}

// Удаляет дочерние элементы элемента с ID, равным node_id
function deleteChildNodes(node_id)
{
	// Отключаем связь с редакторами
	DisableTinyMCE();

	var node = document.getElementById(node_id);

	if (node !== undefined)
	{
		if (node.hasChildNodes())
		{
			while (node.firstChild)
			{
				node.removeChild(node.firstChild);
			}
		}
	}
}

function HideWindow(windowId)
{
	var windowDiv = document.getElementById(windowId);

	if (windowDiv == undefined)
	{
		return false;
	}

	// Окно редактирования элементов ЦА при закрытии - удаляем полностью
	if (windowId.indexOf('edit_window_') == 0)
	{
		// Отключаем связь с редакторами
		DisableTinyMCE();

		// Удаляем дочерние узлы
		deleteChildNodes(windowId);

		// Удаляем окно
		windowDiv.parentNode.removeChild(windowDiv);
	}
	else
	{
		windowDiv.style.display = 'none';
	}
}

// Магазин
function doSetLocation(shop_country_id, path)
{
	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', path + "?action=get_location&shop_country_id="+shop_country_id, true);

	// Отсылаем данные в обработчик.
	req.send(null);

	// Курсор ставим на часики.
	document.body.style.cursor = "wait";
}


function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();


addEvent(window,'unload',EventCache.flush);

function ShowImgWindow(title, src, width, height)

{
        LeftPosition = (screen.width) ? (screen.width - width) / 2 : 100;
        TopPosition = (screen.height) ? (screen.height - height) / 2 : 100;

	obj = window.open("", "", "top="+TopPosition+", left="+LeftPosition+",  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();

}

$(document).ready(function() {


$('.selgroup').click(function() {

if ($(this).hasClass('act')){return false}
$('.selgroup').removeClass('act');
$(this).addClass('act');
var n = $('.selgroup').index(this) + 1;

$('.group1').hide();
$('.group2').hide();
$('.group3').hide();
$('.group4').hide();
$('.group5').hide();
$('.group6').hide();
$('.group7').hide();
$('.group8').hide();
$('.group9').hide();
$('.group10').hide();
$('.group11').hide();
$('.group12').hide();
$('.group13').hide();
$('.group14').hide();
$('.group15').hide();
$('.group16').hide();
$('.group17').hide();
$('.group18').hide();
$('.group19').hide();
$('.group'+n).show();

return false;

}); 
}); 
