var globalCost=0
var globalAmount=0
var globalOrderAmount=0;
var noCart = 0;

function CheckPatern(vdata,patern)
{
  var numStr=patern;
  var thisChar;
  vdata.toLowerCase();
  for (var i=0; i < vdata.length; i++)
  {
    thisChar = vdata.substring(i,i+1);
    if (numStr.indexOf(thisChar) == -1)  return false;
  }
  return true;    
}

function isNumber(vdata)
{
  var numStr="0123456789.";
  return  CheckPatern(vdata,numStr); 
}

function myFixed(x, p)
{
	var s = x.toString()
	var i = s.indexOf(".")
	if (i != -1){
		dec = s.substr(i+1,p)
		s = s.substr(0,i) + "." + dec
	}
	return parseFloat(s);
}

var prec = 10000000000;

function div(a,b)
{
	if (a == b)
		return 1;
	return a*prec/b/prec;
}

function mul(a,b)
{
	return a*prec*b/prec;
}

function calcAmountAndCost(shop, record, amount, nBase, nOrder, nShip, r, c, costType)
{
	var ratios = r.split("/") //цены
	var costs = c.split("/")

	if (nOrder == nShip){
		globalOrderAmount = amount
		globalAmount = amount;
		globalCost = amount * parseFloat(ratios[nShip]/ratios[nBase] * costs[costType])
		return;
	}

	//1. узнаем сколько вмещается заказа в нужной отгрузке
	var r = ratios[nOrder]*prec/ratios[nShip]/prec
//	var shipAmount = myFixed(r,3)*amount;
	var shipAmount = r*amount;
//alert(ratios[nOrder] + "/" + ratios[nShip] + "=" + shipAmount)

	//2. проверим на целоe количество
	if (nShip != nOrder && parseFloat(shipAmount - parseInt(shipAmount)) > 0){
		shipAmount = parseInt(shipAmount) + 1		
	}

	//3. сумма
	//кол-во в баз.ед.
	var shipInBase = div(ratios[nShip], ratios[nBase]);
	amountInBase = mul(shipAmount, shipInBase);
	amountInBase = myFixed(amountInBase, 3);

	//кол-во ед. заказа
	var correlation = parseInt(ratios[nShip]*prec/ratios[nOrder]/prec*1000)/1000;
	globalOrderAmount = correlation * prec * shipAmount/prec
//	alert(correlation + "*" + shipAmount + "=" + globalOrderAmount)

	globalAmount = shipAmount
//	globalCost = (amountInBase*100000)*(costs[costType]*prec)/prec/100000

	globalCost = amountInBase*10000*(costs[costType]*10000000000)

	p = 14
	s = globalCost.toString()	
	globalCost = parseFloat(s.substr(0,s.length-p) + "." + s.substr(s.length-p))

//	alert((amountInBase) + "*" + (costs[costType]) + "=" + globalCost)
//	alert(globalCost.toString())
	//1000000000000000
//	s = globalCost.toString()
//	alert(s.substr(0,15) + "." + s.substr(15))

//	globalCost/=1000000000000000

// после деления расстановку "." делать с помощью строки!
//	alert((amountInBase*100000) + "*" + (costs[costType]*10000000000) + "=" + globalCost)

	globalCost = myFixed(globalCost, 2)
}

function Buy(formId)
{
	var myForm = document.forms("f"+formId)
	if (!myForm)
 		return false;

	myAmount = myForm.amount;

	if (!myAmount)
		return false;

	amount = myAmount.value

	if (!amount || amount == 0 || !isNumber(amount) || (parseFloat(amount) - parseInt(amount) != 0))
	{  
		myAmount.focus();
		alert("Пожалуйста, укажите количество\nвыбранного вами товара. При этом\nвы можете использовать только целые\nчисловые значения.");
		return false;
	}

	amount = parseInt(amount)

	var shop = myForm.shop.value;
	var record = myForm.record.value;

	var units = myForm.units.value.split("/");
	var ratios = myForm.ratios.value.split("/");
	var costs = myForm.costs.value.split("/");

	var baseUnit = myForm.baseUnit.value;
	var orderUnit = myForm.orderUnit.value;
	var shipUnit = myForm.shipUnit.value;

	var nBase = -1;
	for (var i=0; i<units.length; i++){
		if (units[i] == baseUnit){
			nBase = i;
			break;
		}
	}

	var nOrder = -1;
	for (var i=0; i<units.length; i++){
		if (units[i] == orderUnit){
			nOrder = i;
			break;
		}
	}

	var nShip = -1;
	for (var i=0; i<units.length; i++){
		if (units[i] == shipUnit){
			nShip = i;
			break;
		}
	}

	if (nOrder < 0 || nShip < 0 || nBase < 0){
		alert("Величина не задана")
		return false;
	}

	var cart = document.all['dCart']	
	var theName = myForm.theName.value 

	var theValue = shop + "\t" + record + "\t" + amount + "\t" + nBase + "\t" + nOrder + "\t" + nShip + "\t" + myForm.ratios.value + "\t" + myForm.costs.value + "\t" + myForm.units.value
	cart.options[cart.options.length] = new Option(theName,theValue,false,false)

	PrepareCookie()
	calcTotalCost()
//	moveCart()
	var cartForm = document.all['cartForm']
	cartForm.submit()

	return false;
}

function calcRealCosts(type)
{
	var list = document.all['dCart']
	var cost = 0

	for (var i=0; i<list.options.length; i++)
	{
		var theValues = list.options[i].value
		var v = theValues.split("\t")

		calcAmountAndCost(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],type)
		cost += globalCost
	}

	return cost;
}

function calcTotalCost()
{
	var pay = document.all['dPay'].selectedIndex
	var total = document.all['totalCost']
	var discount = 0;
	var discountMsg;
	var type;

	var cost = calcRealCosts(0)
	if (pay == 0){
		if (cost > 10000)
			type = 2
		else
		if (cost >= 5000)
			type = 1
		else
		if (cost < 5000)
			type = 0
	} else {
		if (cost > 25000)
			type = 2
		else
		if (cost >= 10000)
			type = 1
		else
		if (cost < 10000)
			type = 0
	}

	if (type != 0){
		var realCost = calcRealCosts(type)
		discount = cost - realCost
		discount = myFixed(discount, 2)
		cost = realCost
		discountMsg = "<br>" + (type==1?"мелкооптовая":"оптовая") + " цена (скидка " + discount + " руб.)"
	} else {
		discountMsg = "<br>розничная цена"
	}

	var s = "<font color=#2C75AB style='font-size:11px;'><B>ИТОГОВАЯ СТОИМОСТЬ</B>: <font color=#00aa00>" + myFixed(cost,2) + " руб.</font>"
	s += "<font color=#2C75AB style='font-size:11px;'>" + discountMsg + "</font>"

	total.innerHTML = s
}

function deleteFromCart(n)
{
	var list = document.all['dCart']
	if (!n)
		list.selectedIndex = n

	if (n != -1){
		var formId = list.options[n].value
		list.options[n] = null

		calcTotalCost()

		details = document.all['cartDetails']
		details.innerHTML = "&nbsp;"
	}

	PrepareCookie()
	moveCart()
}

function fixFloat(f)
{
	return myFixed(f,3);

	f = parseFloat(f)
	f = myFixed(f,3)
	if (f - parseInt(f) == 0){
		f = parseInt(f)
	}
	return f;
}

function onSelectItem()
{
	var list = document.all['dCart']
	if (list.selectedIndex < 0)
		return;

	var vals = list.options[list.selectedIndex].value
	details = document.all['cartDetails']

	var v = vals.split("\t")
	var r = v[6].split("/")
	var u = v[8].split("/")

	calcAmountAndCost(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],0)

   var s = "Ваш заказ " + v[2] + " " + u[v[4]] + "<br>"
   s += "Вам отгрузят " + myFixed(globalAmount,3) + " " + u[v[5]] + " (" + myFixed(globalOrderAmount,3) + " " + u[v[4]] + ")" + "<br>"
   s += "Стоимость: " + myFixed(globalCost, 2) + " руб."

	details.innerHTML = s
}

function PrepareCookie()
{
	var list = document.all['dCart']
	var cart = ""

	for (var i=0; i<list.options.length; i++)
	{
		var theValues = list.options[i].value
		var v = theValues.split("\t")
		
		cart += v[0] + "\t" + v[1] + "\t" + v[2] + "\t" + v[3] + "\t" + v[4] + "\t" + v[5] + "\n"
	}

	var pay = document.all['dPay'].selectedIndex

	setCookie("cart", cart, 0,"/");
	setCookie("pay", pay, 0,"/");
}

function ProcessOrder()
{
	PrepareCookie();	
	return true;
}

function moveCart()
{
return;
	if (noCart)
		return false;

	var cart = document.all['cartFrame']

	var cartCookie = getCookie("cart")
	if (cartCookie.length < 5)
	{
		cart.style.left = -1000
		cart.style.top = -1000
		return;
	}

	var w = document.body.clientWidth + document.body.scrollLeft
	var h = document.body.clientHeight

	cart.style.left = 0
	cart.style.top = document.body.scrollTop
}

function clrCart()
{
	setCookie("cart", '', 0,"/");
	setCookie("pay", '', 0,"/");

	window.location.replace("go.pl?ishop=show&i=1")
}

function onChangePayment(s)
{
	document.all["dPay"].selectedIndex = s.selectedIndex;
	setCookie("pay", document.all["dPay"].selectedIndex, 0,"/");
	calcTotalCost();
//	alert(document.all["dPay"].selectedIndex)
	document.all["cartForm"].submit()
}
