var DebugEnabled = false; 
var NNDebugEnabled = false;
var CurrencyRate = 1;
var	DefDiscountA;
var	DefDiscountB;
var	DefDiscountC;
var	DefDiscountD;
var	PriceCategory;
var OrderCount = 0;
var OrderPrice = 0;
var OrderPriceWithVat = 0;
var ItemCount = 0;
var DeliveryCount = 0;
var ProductDiscountsForDealers = true;
var CountWasChanged = false;
var PaymentWasChanged = false;
var DeliveryWasChanged = false;
var items = new Array();
var shippingItems = new Array();
var paymentDiscounts = new Array();
var handlingItem;
var Sum1 = 0;
var Sum2 = 0;
var Sum1OD = 0;
var Sum2OD = 0;
var Sum1ODSH = 0;
var Sum2ODSH = 0;
var SelPaymentMethodID = 0;
var SelDeliveryMethodID = 0;
var OrderDiscountBorder = 0;
var OrderDiscountBorderWithVat = false;
var OrderDiscount = 0;
var TotalEvaluated = true;
var SumEvaluated = true;
var CustomerDiscount = 0;
var PaymentCount = 0;
var AreDeliveryPaymentDependencies = false;
var RoundingConst = 100;
var FreePaymentOnFreeShipping = false;
var isFreeShipping = false;

var Shipping1 = 0;
var Shipping2 = 0;

var Handling1 = 0;
var Handling2 = 0;

var Charge=0;
var countDiscount;

var Total1;
var Total2;


function Debugln(Text){
	if (DebugEnabled ){
		var e = document.getElementById('debugText');
		if (e){
			e.innerHTML = e.innerHTML +'<br>'+Text;
		}
	   }
	if (NNDebugEnabled)
		alert(Text);
}
function DebuglnB(Text){
	if ((DebugEnabled)){
		var e = document.getElementById('debugText');
		if (e){
			e.innerHTML = e.innerHTML +'<strong>'+Text+'</strong><br />';
		}
	}
}

function ClearDebug(){
	if ((DebugEnabled) && document.debugText && document.debugText.innerHTML)
	document.debugText.innerHTML = '';
}

function asFloat(value){
	if ( isNaN(parseFloat(value))){
	  return 0;
	}else{
		return parseFloat(value);
	}
}


function isInArray(arr, value){
	//alert('function isInArray(arr='+arr+', value='+value+'), arr.length='+arr.length);
	for (var i=0; i<arr.length; i++){
	
		if (arr[i] == value){
			return true;
		}
	}
return false;
}


function ShippingParams(MethodID, Border, BorderType, BorderWithVat,Type1, Type2, Fixed1, Fixed1WithVat, Fixed2, Fixed2WithVat, Vat){
	this.MethodID = MethodID;
	this.Border = Border;
	this.BorderType = BorderType;
	this.BorderWithVat = BorderWithVat;
	this.Type1 = Type1;
	this.Type2 = Type2;
	this.Fixed1 = Fixed1;
	this.Fixed1WithVat = Fixed1WithVat;
	this.Fixed2 = Fixed2;
	this.Fixed2WithVat = Fixed2WithVat;
	this.Vat = Vat;
	this.HandlingEnabled = true;  // default value, may be changed by function setHandlingAllowedFor
}

function HandlingParams( Border, BorderType, BorderWithVat, Type1, Type2, Fixed1, Fixed1WithVat, Fixed2, Fixed2WithVat, PerPc1, PerPc2, Vat){
	this.Border = Border;
	this.BorderType = BorderType;
	this.BorderWithVat = BorderWithVat;
	this.Type1 = Type1;
	this.Type2 = Type2;
	this.Fixed1 = Fixed1;
	this.Fixed2 = Fixed2;
	this.Fixed1WithVat = Fixed1WithVat;
	this.Fixed2WithVat = Fixed2WithVat;
	this.PerPc1 = PerPc1;
	this.PerPc2 = PerPc2;
	this.Vat = Vat;
}

function DeliveryItem(MethodID, DeliveryName){
	this.MethodID = MethodID;
	this.Name = DeliveryName;
}

function PaymentItem(MethodID, PaymentName){
	this.MethodID = MethodID;
	this.Name = PaymentName;
}

var emptyHandlingItem = new HandlingParams(0,0,0,0,0,0,0,0,0,0,0,0);

function PaymentDiscount(MethodID, Enabled, ConstPart, VarPart){
	this.MethodID = MethodID;
	this.Enabled = Enabled;
	this.ConstPart = ConstPart;
	this.VarPart = VarPart;
}


function StoreItem(ItemID, GroupOrder, FullPrice1, FullPrice2, A, B, C, D, M1, M2, M3, M4, DP1, DP2, AP1,AP2, AP3, AP4, Tax, Discount, SpDiscount, CountInStore, CountInOrder, CountInPacking, isPacking){
	this.ItemID = ItemID;
	this.GroupOrder = GroupOrder;
	this.FullPrice1 = FullPrice1;
	this.FullPrice2 = FullPrice2;
	this.PriceA = A;
	this.PriceB = B;
	this.PriceC = C;
	this.PriceD = D;
	this.Min1 = M1;
	this.Min2 = M2;
	this.Min3 = M3;
	this.Min4 = M4;
	this.DealerPrice1 = DP1;
	this.DealerPrice2 = DP2;
	this.aPrice1 = AP1;
	this.aPrice2 = AP2;
	this.aPrice3 = AP3;
	this.aPrice4 = AP4;
	this.Tax = Tax;
	this.Discount = Discount;
	this.SpDiscount = SpDiscount;
	this.CountInOrder = CountInOrder;
	this.CountInStore = CountInStore;
	this.CustomerPrice1 = 0;
	this.CustomerPrice2 = 0;
	this.CountInPacking = CountInPacking;
	this.isPacking = isPacking;
}


function CountSingleItemPrices(){
	var dPrice = this.FullPrice1;
	var DefDiscount = 0;
	if (PriceCategory !=''){
		if (PriceCategory == 'A'){
			DefDiscount = DefDiscountA;
			dPrice = this.PriceA;
		}
		if (PriceCategory == 'B'){
			DefDiscount = DefDiscountB;
			dPrice = this.PriceB;
		}
		if (PriceCategory == 'C'){
			DefDiscount = DefDiscountC;
			dPrice = this.PriceC;
		}
		if (PriceCategory == 'D'){
			DefDiscount = DefDiscountD;
			dPrice = this.PriceD;
		}
		if ((DefDiscount)>0.89) DefDiscount = DefDiscount / 100;
		
		if (0+dPrice==0){
			dPrice = this.FullPrice1*(1-DefDiscount)
			}
		}
		var Count = this.CountInOrder;
		var fa1, fa2, fa3, fa4;
		var isValid1, isValid2,isValid3, isValid4;
	
		if (this.AmountPriceByDealer ){
			fa1 = asFloat(this.PriceA);
			fa2 = asFloat(this.PriceB);
			fa3 = asFloat(this.PriceC);
			fa4 = asFloat(this.PriceD);
		
			isValid1 = validAmount(this.Min1, this.PriceA);
			isValid2 = validAmount(this.Min2, this.PriceB);
			isValid3 = validAmount(this.Min3, this.PriceC);
			isValid4 = validAmount(this.Min4, this.PriceD);
		}else
		{
			fa1 = asFloat(this.aPrice1);
			fa2 = asFloat(this.aPrice2);
			fa3 = asFloat(this.aPrice3);
			fa4 = asFloat(this.aPrice4);
			//isValid1=validAmount(1,1);
			isValid1 = validAmount(this.Min1, this.aPrice1);
			isValid2 = validAmount(this.Min2, this.aPrice2);
			isValid3 = validAmount(this.Min3, this.aPrice3);
			isValid4 = validAmount(this.Min4, this.aPrice4);
			Debugln(' this.Min1='+this.Min1);
			Debugln(' this.aPrice1='+this.aPrice1);
			Debugln(' this.Min4='+this.Min4);
			Debugln(' this.aPrice4='+this.aPrice4);
		}
	var adPrice = this.FullPrice1;
	if (( (Count >= this.Min1) && isValid1 ) &&  ( (Count<this.Min2) || !(isValid2 ) )){
		Debugln(' is valid FA1: '+fa1);
	   adPrice = fa1; // CurrencyRate;
	}

	if (((Count >= this.Min2) && isValid2 ) && ((Count<this.Min3) || !(isValid3)) ){
		Debugln(' is valid FA2: '+fa2);
	   adPrice = fa2; // CurrencyRate;
	}

	if ( ( (Count >= this.Min3) && isValid3 ) && ( (Count<this.Min4) || !( isValid4 )) ){
		Debugln(' is valid FA3: '+fa3);
	   adPrice = fa3; // CurrencyRate;
	}

	if ((Count >= this.Min4) && isValid4) {
		Debugln(' is valid FA4: '+fa4);
	   adPrice = fa4; // CurrencyRate;
	}

	Debugln('dPrice = '+dPrice);
	Debugln('adPrice = '+adPrice);

	if (adPrice< dPrice) dPrice = adPrice;
	
	this.CustomerPrice1 = dPrice;
	this.CustomerPrice2 = this.CustomerPrice1* ( 1 + this.Tax/100);
	
	Debugln('this.CustomerPrice1=' + this.CustomerPrice1);
	Debugln('this.CustomerPrice2=' + this.CustomerPrice2);

	this.ApplyDiscounts();
	
	Debugln('this.CustomerPrice1=' + this.CustomerPrice1);
	Debugln('this.CustomerPrice2=' + this.CustomerPrice2);
}

function validAmount(amount,price)
{
	//alert("kuk");	
	Debugln('function validAmount('+amount+', '+price+')');
	if ( isNaN(parseFloat(amount)) || isNaN(parseFloat(price)) || (amount==0) ) {
		Debugln(' .. is not valid');
		return false
		}
	else return true;
	
};


function ApplyDiscounts(){
	var canUseDiscount = (PriceCategory == '') || (ProductDiscountsForDealers);
	var Koef = 1;
	Debugln('Product Discount = '+this.Discount);
	Debugln('Product SpDiscount = '+this.SpDiscount);
	var Discount = this.SpDiscount;
	if (canUseDiscount) Discount = Discount + this.Discount;
	Koef = 1-(Discount/100);
	Debugln('  Koef = '+Koef);
	this.CustomerPrice1 = this.CustomerPrice1 * Koef
	this.CustomerPrice2 = this.CustomerPrice1 * (1+this.Tax/100);
	var Koef1 = 1-(CustomerDiscount/100);
	Debugln('Koef1='+Koef1);
	this.CustomerPrice1 = this.CustomerPrice1 * Koef1;
	this.CustomerPrice2 = this.CustomerPrice2 * Koef1;
}


function setHandlingAllowedFor(arr){
	var i;
	//alert('function setHandlingAllowedFor(arr='+arr+')');
	for (i=0;i<DeliveryCount;i++){
		
		bIsAllowed = isInArray(arr, shippingItems[i].MethodID);
	//	alert('Delivery '+shippingItems[i].MethodID+' HandlingEnabled='+bIsAllowed);
		shippingItems[i].HandlingEnabled = bIsAllowed;
	}
}

StoreItem.prototype.ApplyDiscounts = ApplyDiscounts;
StoreItem.prototype.CountSingleItemPrices = CountSingleItemPrices;

function DeliveryPrice(){
	this.Evaluated = true;
	this.Price = 0;
	this.PriceWithVat = 0;
}


function SetFieldValue(FieldName, Value){
	var f = window.document.getElementById(FieldName);
	if (f)
		f.setAttribute('value',  Value);
}

var shippingPrice = new DeliveryPrice();
var handlingPrice = new DeliveryPrice();

function recalculatePrices(){
	Debugln('Function recalculatePrices');
	Sum1 = 0;
	Sum2 = 0;

	OrderCount = 0;
	for (var i=0; i<ItemCount; i++){
		items[i].CountSingleItemPrices();
		Debugln("cena polozky:"+items[i].CustomerPrice1);
		Sum1 = Sum1+items[i].CustomerPrice1 * items[i].CountInOrder;
		Sum2 = Sum2+items[i].CustomerPrice2 * items[i].CountInOrder;
		OrderCount = OrderCount+items[i].CountInOrder;
		Debugln("prubezna sum1: "+Sum1);
		Debugln("prubezna sum2: "+Sum2);
		
	}
	Sum1 = Math.round(Sum1*100)/100;
	Sum2 = Math.round(Sum2*100)/100;
	Debugln('Sum1 = '+Sum1);
	Debugln('Sum2 = '+Sum2);
	Discount = GetOrderDiscount();
	countDiscount=Discount;
	if (Discount !=0)
	Sum1OD = Sum1 * (1 - Discount/100);
	Sum2OD = Sum2 * (1 - Discount/100);
	recalculateShipping();
	recalculateHandling();
	ShippingHandlingChanged();
}

function writenewPrices() {
//return;
if (window.document.Form1 && window.document.Form1.newDiscount){
	window.document.Form1.newDiscount.value = rounding(countDiscount);
}else{
	SetFieldValue('newDiscount', rounding(countDiscount));
};

if (window.document.Form1 && window.document.Form1.newPrice){
	Debugln("sum1 pred vypisem," + Sum1)
	window.document.Form1.newPrice.value = rounding(Sum1)
}else{
	SetFieldValue('newPrice', rounding(Sum1));
};	
	
if (window.document.Form1 && window.document.Form1.newPricewithTax){
	Debugln("sum2 pred vypisem," + Sum2)
	window.document.Form1.newPricewithTax.value = rounding(Sum2)
}else{
	SetFieldValue('newPriceWithTax', rounding(Sum2));
};

if (window.document.Form1 && window.document.Form1.newPriceDisc){
	window.document.Form1.newPriceDisc.value=rounding(Sum1OD)
}else{
	SetFieldValue('newPriceDisc', rounding(Sum1OD));
};

if (window.document.Form1 && window.document.Form1.newPricewithTaxDisc){
	window.document.Form1.newPricewithTaxDisc.value=rounding(Sum2OD)
}else{
	SetFieldValue('newPriceWithTaxDisc', rounding(Sum2OD));
};

if (window.document.Form1 && window.document.Form1.showShipping){
	window.document.Form1.showShipping.value=rounding(Shipping1)
}else{
	SetFieldValue('showShipping', rounding(Shipping1));
};

if (window.document.Form1 && window.document.Form1.showShippingwithtax){
	window.document.Form1.showShippingwithtax.value=rounding(Shipping2)
}else{
	SetFieldValue('showShippingWithTax', rounding(Shipping2));
};

if (window.document.Form1 && window.document.Form1.showhandling){
	window.document.Form1.showhandling.value=rounding(Handling1);
}else{
	SetFieldValue('showHandling', rounding(Handling1));
};

if (window.document.Form1 && window.document.Form1.showhandlingwithtax){
	window.document.Form1.showhandlingwithtax.value=rounding(Handling2);
}else{
	SetFieldValue('showHandlingWithTax', rounding(Handling2));
};

if (window.document.Form1 && window.document.Form1.pricewithshippingwithtax){
	window.document.Form1.pricewithshippingwithtax.value=rounding(Sum2ODSH);
}else{
	SetFieldValue('priceWithShippingWithTax', rounding(Sum2ODSH));
};

if (window.document.Form1 && window.document.Form1.pricewithshipping){
	window.document.Form1.pricewithshipping.value=rounding(Sum1ODSH);
}else{
	SetFieldValue('priceWithShipping', rounding(Sum1ODSH));
};	
	
if (window.document.Form1 && window.document.Form1.charge){
	window.document.Form1.charge.value=rounding(Total1-Sum1ODSH);
}else{
	SetFieldValue('charge', rounding(Total1-Sum1ODSH));
};	

if (window.document.Form1 && window.document.Form1.chargewithtax){
	window.document.Form1.chargewithtax.value=rounding(Total2-Sum2ODSH);
}else{
	SetFieldValue('chargeWithTax', rounding(Total2-Sum2ODSH));
};	
		
if (window.document.Form1 && window.document.Form1.totalprice){
	window.document.Form1.totalprice.value=rounding(Total1);
}else{
	SetFieldValue('totalPrice', rounding(Total1));
};	
	
if (window.document.Form1 && window.document.Form1.totalpricewithtax){
	Debugln("setting TOTAL WITH TAX: "+Total2);
	window.document.Form1.totalpricewithtax.value=rounding(Total2);
}else{
	SetFieldValue('totalPriceWithTax', rounding(Total2));
};				
};

function rounding(hodnota) {
//alert("KUK1 " + hodnota)
var roundV= Math.round(hodnota * RoundingConst) / RoundingConst;
if (isNaN(roundV)){roundV='???'};
//alert("KUK2 " + roundV)
return roundV;


};


function countChanged(field){
	CountWasChanged = true;
	ClearDebug();
Debugln('');
Debugln('<b>function countChanged()</b>');
Debugln("field "+field)
	var index = 0;
	var NeedRecalculate = false;
	var s = '';
	s = field.name;
	ItemID = 0;
	Debugln('field name = '+s);
	index = s.indexOf(';ItemID=');
	if (index>0){
		s = s.substr(index+8);
	}
	Debugln('ItemID='+s);
	index = s.indexOf(';');
	if (index>0){
		s = s.substr(0, index);
	}
	Debugln('ItemID='+s);
	ItemID = parseInt(s);
	
	var sValue;
	if (field.value){
		sValue = field.value.replace(',','.')
	}else{
		sValue = field.getAttribute('value');
	}
	
	Debugln('ItemID='+ItemID+', Value = '+sValue);
	
	NewCount = parseFloat(sValue);
	for (i=0; i<ItemCount; i++){
		Debugln('itemsId = '+items[i].ItemID+', Old Count = '+items[i].CountInOrder+', New Count = '+NewCount);
		if (items[i].ItemID == ItemID){
			if (items[i].isPacking) NewCount = NewCount * items[i].CountInPacking;
			if (items[i].CountInOrder != NewCount){
				items[i].CountInOrder = NewCount;
				if (items[i].GroupOrder >0 ) SumEvaluated = false;
				NeedRecalculate = true;
			}
			break;
		}
	}
	if (NeedRecalculate){
		EnableButtonRecalculate();
		recalculatePrices();
		ShippingHandlingChanged();
		TotalChanged();
		writenewPrices();
	}else{
		Debugln('recalculation not needed')
	}
}


function EnableButtonRecalculate(){
	if (document.Form1 && document.Form1.ButtonChange && document.Form1.ButtonChange.disabled)	
		document.Form1.ButtonChange.disabled = false
	else{
		var f = document.getElementById('ButtonChange');
		if (f )
			f.setAttribute('disabled', false);
	}

}

function pointsChanged(){
		EnableButtonRecalculate();
		recalculatePrices();
		ShippingHandlingChanged();
		TotalChanged();
		writenewPrices();
}

function GetOrderDiscount(){
	Debugln('function GetOrderDiscount()');
	var Value;
	if (OrderDiscountBorderWithVat){
		Value = Sum2
	}
	else
	{
		Value = Sum1
	}
	if ( Value< OrderDiscountBorder / CurrencyRate){
		return 0;
	}
	else
	{
		return OrderDiscount;
	}
}

// on delivery change
function DeliveryChanged(select){
	Debugln('');
	DebuglnB('--Function DeliveryChanged()');
	DeliveryWasChanged = true;
	EnableButtonRecalculate();
	var NewId = select.value;
	Debugln('New delivery method = ' + NewId);
	SelDeliveryMethodID = NewId;
	if (AreDeliveryPaymentDependencies){
		if ((DeliveryPaymentDependencyType=='delivery') || (DeliveryPaymentDependencyType=='')){
			RefillPaymentSelection(true);
		}
		if (DeliveryPaymentDependencyType==''){  // fill-in all deliveries
			RefillDeliverySelection(false);
		}
	}
	recalcAfterDeliveryChanged();
}

function recalcAfterDeliveryChanged(){
	recalculatePrices();
	ShippingHandlingChanged();
	TotalChanged();
	writenewPrices();
}


// on payment change
function PaymentChanged(select){
	DebuglnB('--Function PaymentChanged()');
	EnableButtonRecalculate();
	PaymentWasChanged = true;
	var NewId = select.value;
	Debugln('New delivery method = ' + NewId);
	SelPaymentMethodID = NewId;
	if (AreDeliveryPaymentDependencies){
		Debugln('DeliveryPaymentDependencyType='+DeliveryPaymentDependencyType);
		if ((DeliveryPaymentDependencyType=='payment') || (DeliveryPaymentDependencyType=='')){
			Debugln('..calling RefillDeliverySelection');
			RefillDeliverySelection(true);
		}
		if (DeliveryPaymentDependencyType==''){  // fill-in all payments
			RefillPaymentSelection(false);
		}
	}
	recalcAfterPaymentChanged();
}


function recalcAfterPaymentChanged(){
	recalculatePrices();
	ShippingHandlingChanged();
	TotalChanged();
	writenewPrices();
}


function recalculateShipping(){
	var i;
	for (i=0; i<DeliveryCount; i++){
		if (shippingItems[i].MethodID == SelDeliveryMethodID){
			var Params = shippingItems[i];
			calculateShipping(Params);
		