bV=parseInt(navigator.appVersion); ie4 = (document.all)? true:false;
var http = createRequestObject();
// Переменные для смены картнок в одном товаре
var allfoto; var cur_cat_id;
var Width = new Array;
var Height = new Array;
var cur_tov_id; var itogo;
var flag_next=1;
var A=new Array; var A_old=new Array; var B=new Array; var C=new Array; var C_copy=new Array; var W=new Array; var H=new Array;
var update_global = new Array();
var kkk=0;
var flag_record=1;
var glob_currency;
var currency_name;     //наименование валюты товара
var nameFunctionAfterAjax;
// A - хранит цены
// A_old - хранит старые цены
// B - хранит количества
// C - хранит id
// W - хранит ширину картинок
// H - хранит высоту картинок
////////////////////////////////////////////////

function createRequestObject()
{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer") ro = new ActiveXObject("Microsoft.XMLHTTP");
    else ro = new XMLHttpRequest();
    return ro;
}
function goAjax(url)
{
    http.open("get", url);
   	http.onreadystatechange = handleResponse;
    http.send(null);
}
function handleResponse()
{
    if(http.readyState == 4)
	{
        var response = http.responseText;
        var update = new Array();
        if(response.indexOf('|' != -1))
		{
            update = response.split('|');
			if (update[5]=="many")
			{
				flag_next=1;
				update_global=update;
				ORDER_TOVAR2(glob_currency);
			}
			else
			{
				length_=update.length;
				for (i=0; i<length_; i=i+2)
				{
//					alert(update[i]+"---"+update[i+1])
					if (document.getElementById(update[i]))
					{
						document.getElementById(update[i]).innerHTML = update[i+1];
					}
				}
			}
        }
        if (nameFunctionAfterAjax) oneblur = setTimeout(nameFunctionAfterAjax, 0);
        nameFunctionAfterAjax = "";
    }
}
function MENU(num)
{
	if (num>0)
	{
		if (document.getElementById("n2_"+num).style.display!="inline")
		{
			Hidden("n2_"+num, "inline");
			document.getElementById("n1_"+num).innerHTML='<a href="javascript:MENU('+num+');" id="n1a_'+num+'">'+document.getElementById("n1a_"+num).innerHTML+'</a>';
			ChangeBG("n1_"+num, "/img/rus/minus.gif");
			ChangeBG("n1a_"+num, "/img/rus/fonm1_.jpg");
		}
		else
		{
			Hidden("n2_"+num, "none");
			ChangeBG("n1_"+num, "/img/rus/plus.gif");
			ChangeBG("n1a_"+num, "/img/rus/fonm2_.jpg");
		}
	}
}
function OneTov(mode, id, cat_id, type, event, coorX, type_complect)
{
	if (!type_complect) type_complect=0;
	if (mode==2)
	{
		Hidden("onebigtovar2", "none");
		Hidden("overlay", "none");
		document.getElementById("onebigtovar2").innerHTML = "";
	}
	else
	{
		if (!event) event=window.event;
		coorY=event.clientY;
		flag=drowWindow(coorY, type, coorX);
		document.getElementById("onebigtovar2").innerHTML='Информация загружается...<div id="close"><a href="javascript:OneTov(2);">Закрыть</a></div><br><br><br><br><br><br>';

		var pW = getPageSize();
		var x = document.body.clientWidth-2;
		pW[1]-=88;
		var y = document.body.scrollTop;
		document.getElementById("overlay").style.width = x+"px";
		document.getElementById("overlay").style.height = pW[1]+"px";
		Hidden("overlay", "inline");

		url="/misc/onetov.php?id="+id+"&cat_id="+cat_id+"&flag="+flag+"&type_complect="+type_complect;
		goAjax(url);
	}
}
function drowWindow(ClickCoorY, type, coorX)
{
	if (coorX==0)
	{
		if (type==1) minus=280;
		if (type==2) minus=380;
		flag=1;
	}
	else {minus=coorX; flag=0;}

	var y = document.documentElement.scrollTop;
	coorY=document.documentElement.scrollTop+ClickCoorY-minus;

	document.getElementById("onebigtovar2").style.top = coorY+"px";
	Hidden("onebigtovar2", "inline");
	return flag;
}
function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function Hidden(id, style)
{
	if (document.getElementById(id))
	{
		if (style == "table-row")
		{
				if (ie4) document.getElementById(id).style.display=style;
				else document.getElementById(id).style.display="inline";
		}
		else
		document.getElementById(id).style.display=style;
	}
}
function ChangeBG(id, color)
{
	document.getElementById(id).style.backgroundImage='url("'+color+'")';
}
function ORDER_TOVAR(mode, id, price, cat_id, w_simg, h_simg, regime, number, type, currency)
{
	flag=true;
	if (mode=="recount")
	{
		recount_id=id;
		url="/misc/db_basket.php?id="+id+"&mode="+mode+"&number=";
		oneblur=setTimeout("Blur()", 0); //  в одной функции не хочет на лету менять количество, пришлось вынести в функцию Blur
	}
	if (mode=="delone")
	{
		url="/misc/db_basket.php?del_id="+id+"&mode="+mode;
		goAjax(url);
	}
	if (mode=="delall")
	{
    	document.TovarsInBasket.mode.value=mode;
    	document.TovarsInBasket.action="/misc/db_basket.php";
	    document.TovarsInBasket.submit();
	}

	if (mode=="add")
	{
		if (regime=="3") number_s=number;
		else
		{
			if (regime=="2") number_s=document.getElementById("numberfororder"+id).value;
			else           number_s=parseInt(document.getElementById("numberfororder").value);
		}
//		alert(id);
		if (type!="many") type="one";
		params="id|"+id+"|cat_id|"+cat_id+"|w_simg|"+w_simg+"|h_simg|"+h_simg+"|price|"+price+"|number|"+number_s+"|c|"+currency;
		url="/misc/db_basket.php?params="+params+"&cat_id="+cat_id+"&id="+id+"&type="+type;
		goAjax(url);
//		window.open("/misc/order.php", "wOrder", "width=300, height=200, left=300, top=300, status=no, toolbar=no, menubar=no, scrollbars=no, resizable=no");
	}
}
function ORDER_TOVAR2(currency)
{
	if (currency!="") glob_currency=currency;
	var item=0;
//	alert(C_copy.length+"--"+C.length)
	for(jj=0; jj<C_copy.length; jj++)
	{
		kkk++;
//		alert(C[item]+"---"+jj);
		if (C_copy.length==1) type="one";
		else type="many";
		if (B[C_copy[item]]>0 && flag_next)
		{
			flag_next=0;
			ORDER_TOVAR("add", C_copy[item], A[C_copy[item]], cur_cat_id, W[C_copy[item]], H[C_copy[item]], 3, B[C_copy[item]], type, glob_currency);
			C_copy.shift();
			return; // выход из функции, чтобы вовзрат в эту функцию происходил ТОЛЬКО после занесения товара в корзину
		}
		else
		{
//			alert("////////////////"+B[C_copy[item]]+"==="+C_copy.length+"-"+flag_next)
			C_copy.shift();
		}
	}
//	alert(C_copy.length)
	if (C_copy.length==0)
	{
		CopyArrays();
		document.getElementById(update_global[0]).innerHTML = update_global[1];
//		document.getElementById(update_global[2]).innerHTML = update_global[3];
	}
	else {ORDER_TOVAR2(glob_currency);}
}
function Blur() // функция для обработки вводимого количества товаров
{
	re = /^\.$/;
	re4 = /^[\d \-\+\(\)]+$/;
	clearTimeout(oneblur);
	document.TovarsInBasket['number['+recount_id+']'].blur();
	document.TovarsInBasket['number['+recount_id+']'].focus();
	num=document.TovarsInBasket['number['+recount_id+']'].value;
	if (num>100000) num=100000;
	if (!re4.test(num)) num=0;
	document.getElementById("amount"+recount_id).innerHTML = num;
	onesum=num*document.getElementById("price"+recount_id).innerHTML;
	if (!re.test(onesum)) onesum=onesum+".00";
	document.getElementById("pricesum"+recount_id).innerHTML = onesum;
	url=url+num;
	goAjax(url);
}
function Blur2()
{
	re4 = /^[\d \-\+\(\)]+$/;
	re5 = /^\.$/;
	B[cur_tov_id]=document.getElementById("numberfororder"+cur_tov_id).value;
	if (!re4.test(B[cur_tov_id]))
	{
		B[cur_tov_id]=0;
		document.getElementById("numberfororder"+cur_tov_id).value = 0;
	}
	PaintFieldTov(cur_tov_id);
}
function PaintFieldTov(tov_id)
{	if (document.getElementById("tovar"+tov_id))
	{
		if (document.getElementById("numberfororder"+tov_id).value==0)	document.getElementById("tovar"+tov_id).style.backgroundColor='#FFFFFF';
		else															document.getElementById("tovar"+tov_id).style.backgroundColor='#FFECA7';
	}
}
function zeroPad(number, size) {
   number = String(((number%1)*100).toFixed());
   return (1 << Math.max(size - number.length, 0)).toString(2).slice(1) + number;
}
function Move()
{
/*	if (!flag_spilka)
	document.getElementById("head").style.top=document.documentElement.scrollTop+"px";*/
}
function OnOffMoving()
{
	if (!flag_spilka)
	{
		document.getElementById("head").style.top="0px";
//		document.images("spilka").src="/img/rus/spilka1.gif";
		if (document.getElementById("spilka0")) {document.getElementById("spilka0").style.backgroundImage='url("/img/rus/spilka1.gif")';}
		if (document.getElementById("spilka1")) document.getElementById("spilka1").style.backgroundImage='url("/img/rus/spilka1.gif")';
		flag_spilka=1;
	}
	else
	{
		if (document.getElementById("spilka0")) document.getElementById("spilka0").style.backgroundImage='url("/img/rus/spilka0.gif")';
		if (document.getElementById("spilka1")) document.getElementById("spilka1").style.backgroundImage='url("/img/rus/spilka0.gif")';
		flag_spilka=0;
	}
	url="/misc/onoffmoving.php";
	goAjax(url);
}
function Sort(mode, orders)
{
	if (mode==2)
	{
		document.search.orders.value=orders; // если в поиске осуществляется сортировка
		document.search.submit();
	}
	else
	document.ListTovars.submit();
}
function OK()
{
	flag=true;
	re = /^\s*$/;
	if (document.getElementById("b_amount"))
	if (document.getElementById("b_amount").innerHTML==0)
	{
		alert("Количество товара должно быть не менее одной единицы");
		flag=false;
		return;
	}
	if (re.test(document.Data3.contact.value) || document.Data3.contact.value=="*Имя")
	{
		alert("Введите имя");
		flag=false;
		return;
	}
	if (re.test(document.Data3.phone.value) || document.Data3.phone.value=="*Телефон")
	{
		alert("Введите контактный телефон");
		flag = false;
		return;
	}
	if (flag)
	{
		document.Data3.sent.value="1";
		document.Data3.order.value="basket";
		document.Data3.submit();
	}
}
function PrintOrder()
{
	re3= /([^<)\s]+@\S+\.[^>(\s]+)/;
	if (!re3.test(document.Send.email.value))
	{
		alert("Введите электронный адрес")
		return;
	}
	else
	{
		W=window.open("", "SendOrder","width=300, height=200, left=300, top=300, status=no, toolbar=no, menubar=no, scrollbars=no, resizable=no");
		document.Send.submit();
	}
}
function ChangeFoto(id, mode)
{
	if (mode==1) document.images["img"+id].src="/misc/tovimg.php?id="+id+"&mode=4";
	if (mode==2) document.images["img"+id].src="/misc/tovimg.php?id="+id+"&mode=3";
}
var foto_pos=1;
function Foto(mode, id)
{
	if (mode==1)
	{
		if (foto_pos>1)
		{
			foto_pos--;
			document.getElementById("numfoto").innerHTML=foto_pos;
			document.getElementById("oneimg").innerHTML='<a href="/misc/tovimg.php?id='+id+'&mode=2&cur='+foto_pos+'" class="highslide" onclick="return hs.expand(this)"><img src="/misc/tovimg.php?id='+id+'&mode=2&cur='+foto_pos+'" width="'+Width[foto_pos]+'" height="'+Height[foto_pos]+'" /></a>';
		}
	}
	if (mode==2)
	{
		if (foto_pos<allfoto)
		{
			foto_pos++;
			document.getElementById("numfoto").innerHTML=foto_pos;
			document.getElementById("oneimg").innerHTML='<a href="/misc/tovimg.php?id='+id+'&mode=2&cur='+foto_pos+'" class="highslide" onclick="return hs.expand(this)"><img src="/misc/tovimg.php?id='+id+'&mode=2&cur='+foto_pos+'" width="'+Width[foto_pos]+'" height="'+Height[foto_pos]+'" /></a>';
		}
	}
}
function Inizialize(num, mode)
{
	switch (mode)
	{		case 1: allfoto=parseInt(num)
		break
		case 2: cur_cat_id=num
		break
		case 3: currency_name=num
	}
}
function Inizialize2(numorder, value, mode)
{
	if (mode=="w") Width[numorder]=value;
	if (mode=="h") Height[numorder]=value;
}
function RECOUNT_TIMEOUT()
{	itogo=0; itogo_old=0;
	for(var item in A)
	{
		if (item==cur_tov_id)
		{
			Blur2();
		}

        summa_tov=parseFloat(A[item]*B[item]);
		if (parseFloat(A_old[item])) summa_old=parseFloat(A_old[item]*B[item]);
		else summa_old = summa_tov;
		itogo=itogo+summa_tov;
		itogo_old=itogo_old+summa_old;
  	}

	document.getElementById("itogo_one_tov").innerHTML = Math.floor(itogo)+"<sup>"+zeroPad(itogo, 2)+"&nbsp;</sup>"+currency_name;
	if (document.getElementById("itogo_one_tov_old"))
		{
			if (itogo == itogo_old) document.getElementById("itogo_one_tov_old").innerHTML = "";
			else document.getElementById("itogo_one_tov_old").innerHTML = Math.floor(itogo_old)+"<sup>"+zeroPad(itogo_old, 2)+"&nbsp;</sup>"+currency_name;
		}
}
function RECOUNT(tov_id)
{
	cur_tov_id = tov_id;
	//функция должна вызываться с задержкой, т.к. изменяемые в input данные не успевают попасть в код выполнения
	oneblur = setTimeout("RECOUNT_TIMEOUT()", 0);
}
function Arrays(MAS)
{
	k=1; i=0;
	for(var item in MAS)
	{
		if (k==1) {tov_id=MAS[item]; C[i]=tov_id;  i++;}
		if (k==2) A[tov_id]=MAS[item];
		if (k==3) A_old[tov_id]=MAS[item];
		if (k==4) B[tov_id]=MAS[item];
		if (k==5) W[tov_id]=MAS[item];
		if (k==6) {H[tov_id]=MAS[item]; k=0;}
		k++;
	}
	CopyArrays();
}
function CopyArrays()
{
	for(var item in C)
	C_copy[item]=C[item];
}

////////////////////////////// Тень

function getPageSize()
{
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY)
	{
		xScroll = document.body.scrollWidth;
		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
	{
		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 = windowWidth;
	else pageWidth = xScroll;

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}
function Resize(event)
{
	if (document.getElementById("overlay").style.display=="inline")
	{
		var pW = getPageSize();
		document.documentElement.scrollLeft = 10000; // Определяем размер скролла
		var x = document.documentElement.scrollLeft+document.body.clientWidth;;
		document.documentElement.scrollLeft = 0; // И возвращаем скроллер обратно в ноль

		document.getElementById("overlay").style.width = x+"px";
		document.getElementById("overlay").style.height = pW[1]+"px";
	}
}

///////////////////////////////////////////////////////////////////////////////
function GetBold(id)
{
	if (document.getElementById("adv_search_filters"+id).value!=0)
	document.getElementById("adv_search_filters"+id).style.fontWeight="bold";
	else document.getElementById("adv_search_filters"+id).style.fontWeight="normal";
}
function UpdateTovAmount()
{	for(var item in C)
	{		tov_id = C[item];
		document.getElementById("numberfororder"+tov_id).value = B[tov_id];
		PaintFieldTov(tov_id);
	}
}
function GetOneTov(id, mode)
{
	url="/misc/gettovars.php?id="+id+"&m="+mode;
	goAjax(url);
	//после переключения закладок надо восстановить количества в полях ввода, т.к. они идут "по умолчанию"
	nameFunctionAfterAjax = "UpdateTovAmount()";
}

