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);
			break;			
		}
	}
}

function recalculateHandling(){
	var i;
	var e = false;
	for (i=0; i<DeliveryCount; i++){
		if (shippingItems[i].MethodID == SelDeliveryMethodID){
			var Params = shippingItems[i];
			if (Params.HandlingEnabled){
				calculateHandling(handlingItem);
				e = true;
			}
		break;
		}
	}
	if (!e){
		calculateHandling(emptyHandlingItem);
	}
}


function calculateShipping(Params){
	var Value;
	Debugln('Function calculateShipping()');
	if (isFreeShipping){
		Debugln('..shipping is free for all order');
		shipingPrice.Evaluated = true;
		shippingPrice.Price = 0;
		shippingPriceWithVat = 0;
		return;
	}
	if (Params.BorderType == 0){
		Value = OrderCount;
	}
	else
	{
		if (Params.BorderWithVat){
			Value = Sum2OD;
		}
		else
		{
			Value = Sum1OD;
		}
	}
//	this.Type1 = Type1;
//	this.Type2 = Type2;
//	this.Fixed1 = Fixed1;
//	this.Fixed1WithVat = Fixed1WithVat;
//	this.Fixed2 = Fixed2;
//	this.Fixed2WithVat = Fixed2WithVat;
	
	var Type, Fixed, FixedWithVat;
	
	if (Value<Params.Border){
		Type = Params.Type1;
		Fixed = Params.Fixed1;
		FixedWithVat = Params.Fixed1WithVat;
	}
	else
	{
		Type = Params.Type2	;
		Fixed = Params.Fixed2;
		FixedWithVat = Params.Fixed2WithVat;
	}
	
	if (Type ==0) { // is fixed tariff
		shippingPrice.Evaluated = true;
		shippingPrice.Price = Fixed / CurrencyRate ;
		shippingPrice.PriceWithVat = FixedWithVat / CurrencyRate ;
	}
	else
	{
		shippingPrice.Evaluated = false;
		shippingPrice.Price = '???';
		shippingPrice.PriceWithVat = '???';
	}
	Debugln('Shipping: Evaluated = ' + shippingPrice.Evaluated);
	Shipping1=shippingPrice.Price;
	Shipping2=shippingPrice.PriceWithVat;
}

function calculateHandling(Params){
	var Value;
	Debugln('Function calculateHandling()');
	if (Params.BorderType == 0){
		Debugln('OrderCount = '+OrderCount);
		Value = OrderCount;
	}
	else
	{
		if (Params.BorderWithVat){
			Value = Sum2OD;
		}
		else
		{
			Value = Sum1OD;
		}
	}
	
	var Type, Fixed, FixedWithVat, PerPc;
	Debugln('Handling border = '+Params.Border);
	if (Value<Params.Border){
		Type = Params.Type1;
		Fixed = Params.Fixed1;
		FixedWithVat = Params.Fixed1WithVat;
		PerPc = Params.PerPc1;
	}
	else
	{
		Type = Params.Type2	;
		Fixed = Params.Fixed2;
		FixedWithVat = Params.Fixed2WithVat;
		PerPc = Params.PerPc2;
	}
	
	if (Type ==0) { // is fixed tariff
		if (PerPc){
			Fixed = Fixed * OrderCount;
			FixedWithVat = FixedWithVat * OrderCount;
		}
		handlingPrice.Evaluated = true;
		handlingPrice.Price = Fixed / CurrencyRate ;
		handlingPrice.PriceWithVat = FixedWithVat / CurrencyRate ;
	
	}
	else
	{
		handlingPrice.Evaluated = false;
		handlingPrice.Price = "??";
		handlingPrice.PriceWithVat = "??";
		
	};
	Debugln('Handling: Evaluated = '+handlingPrice.Evaluated);
	Handling1=handlingPrice.Price; 
	Handling2=handlingPrice.PriceWithVat; 
	
}


function ShippingHandlingChanged(){
	DebuglnB('--function ShippingHandlingChanged()');
	Sum1ODSH = Sum1OD;
	Sum2ODSH = Sum2OD;
	if (shippingPrice.Evaluated && handlingPrice.Evaluated){
	
		Sum1ODSH = Sum1ODSH + shippingPrice.Price;
		Sum2ODSH = Sum2ODSH + shippingPrice.PriceWithVat;
		Sum1ODSH = Sum1ODSH + handlingPrice.Price;
		Sum2ODSH = Sum2ODSH + handlingPrice.PriceWithVat;
	}
	else
	{
		Sum1ODSH = '???';
		Sum2ODSH = '???';
	}
	
	Debugln('Shipping=' +shippingPrice.Price+ ', Shippingwithtax = ' + shippingPrice.PriceWithVat);
	Debugln('handling=' +handlingPrice.Price+ ', Handlingwithtax = ' + handlingPrice.PriceWithVat);
	Debugln('Sum1ODSH = '+Sum1ODSH+', Sum2ODSH = '+Sum2ODSH);
	Handling1=handlingPrice.Price;
	Handling2=handlingPrice.PriceWithVat;
	Shipping1=shippingPrice.Price;
	Shipping2=shippingPrice.PriceWithVat;
	if (document.ShowShipping)
		document.ShowShipping.innerText = shippingPrice.Price;
	
	if (document.Form1 && document.Form1.ShowShipping)
		document.Form1.ShowShipping.value = shippingPrice.Price
	else{
		SetFieldValue('showShipping', shippingPrice.Price);
	}

	if (document.ShowShippingWithVat)
		document.ShowShippingWithVat.innerText = shippingPrice.PriceWithVat;

	if (document.Form1 && document.Form1.ShowShippingWithVat)
		document.Form1.ShowShippingWithVat.value = shippingPrice.PriceWithVat
	else{
		SetFieldValue('showShippingWithVat', shippingPrice.PriceWithVat);
	}
		
	if (document.ShowHandling)
		document.ShowHandling.innerText = handlingPrice.Price;
	if (document.ShowHandlingWithVat)
		document.ShowHandlingWithVat.innerText = handlingPrice.PriceWithVat;

	if (document.Form1 && document.Form1.ShowHandling)
		document.Form1.ShowHandling.value = handlingPrice.Price
	else{
		SetFieldValue('showHandling', handlingPrice.Price);
	}
	if (document.Form1 && document.Form1.ShowHandlingWithVat)
		document.Form1.ShowHandlingWithVat.value = handlingPrice.PriceWithVat
	else{
		SetFieldValue('showHandlingWithVat', handlingPrice.PriceWithVat);
	}

	TotalChanged();
}



function GetPaymentDiscount(){
Debugln('function GetPaymentDiscount()');
	for (var i=0;i<PaymentCount; i++){
		if (paymentDiscounts[i].MethodID == SelPaymentMethodID){
			var discount = paymentDiscounts[i];
			if (discount.Enabled != true) {
				 discount.ConstPart = 0;
				 discount.VarPart = 0;
			}		
			return discount;
		}
	}
	return new PaymentDiscount(0, false, 0,0);
}


function TotalChanged(){
	DebuglnB('--function TotalChanged()');
	Debugln('SumEvaluated = '+SumEvaluated);
	if (SumEvaluated && shippingPrice.Evaluated && handlingPrice.Evaluated){
		discount = GetPaymentDiscount();
		Debugln('ConstPart = '+discount.ConstPart+', VarPart = '+discount.VarPart);
		if (discount.VarPart==0) 
		{
			Charge=discount.ConstPart;
		}
		else
		{
			Charge=discount.VarPart + " % ";
		};
		if (FreePaymentOnFreeShipping && shippingPrice.Evaluated && (shippingPrice.Price == 0)){
				Debugln('..PaymentDiscount.ConstPart='+discount.ConstPart+', but Shipping is free, setting PaymentDiscount=0')
				Total1 = Sum1ODSH;
				Total2 = Sum2ODSH;
			}
		else
		{
			Total1 = Sum1ODSH * (1+discount.VarPart/100);// + discount.ConstPart;
			Total2 = Sum2ODSH * (1+discount.VarPart/100) + discount.ConstPart;
		}
		TotalEvaluated = true;
	}
	else
	{
		TotalEvaluated = false;
		Total1 = '???';
		Total2 = '???';
	}
	Debugln('Total1 = '+Total1+', Total2 = '+Total2+', TotalEvaluated = '+TotalEvaluated);
}

function SubmitOrder(Form, msgRecalculate){
	DebuglnB(' Function SubmitOrder()');
	Debugln('TotalEvaluated = '+ TotalEvaluated);
	if (!Form) return true;
	if (!Form.ButtonSubmit) return true;
	if (Form.ButtonSubmit.type=='image')
		var isSubmit = Form.ButtonSubmit.x !=''
	else
		var isSubmit = Form.ButtonSubmit.value !='';
	if (!TotalEvaluated && !isSubmit){
		var msg;
		if (msgRecalculate == '') {
			msg = 'Order was not recalculated correctly because of some changes. \nDo you wish recalculate now?';
		}else{
			msg = msgRecalculate;
		}
		var confirmation = confirm(msg);
		Debugln('Confirmation = '+confirmation);
		if (confirmation){
			Form.action='change_order.asp?url=checkout.asp';
			return true;
		}
		return true;
	}
	else
	{
		return true;
	}
}


function RefillDeliverySelection(ByPayment){
	DebuglnB('RefillDeliverySelection(ByPayment='+ByPayment+')');
	var select = document.getElementById('comboDeliveryMethodID');
	var newSelIndex = -1;
	if (select){
		for (var i = select.options.length - 1; i >= 0; i--){
    		select.options[i] = null;
    	}
    	
    	// alert('DeliveryCount='+DeliveryCount);
    	var k = 0;
		for (var i=0; i<DeliveryCount; i++){
			var isDisabled = false;
			// alert('checking method '+deliveryItems[i].Name);
			if (ByPayment) {
				isDisabled = isDeliveryPaymentDisabled( deliveryItems[i].MethodID, SelPaymentMethodID );
			}
			if (!isDisabled) {
				select.options[k] = new Option( deliveryItems[i].Name, deliveryItems[i].MethodID);
				if (SelDeliveryMethodID == deliveryItems[i].MethodID){
					newSelIndex = k;
				}
				k++;
			}
		}
		if (newSelIndex != -1){
			// mark last selected value as selected in rebuilt list
			select.options[newSelIndex].selected = true;
		}else{
			// mark first as new selected delivery method, so recalculate delivery prices
			if (k>0){
				select.options[0].selected = true;
				SelDeliveryMethodID = select.options[0].value;
				recalcAfterDeliveryChanged();	
			}
		}
	}else{
	
    	var k = 0;
    	var firstEnabled = null;
    	var selectedDisabled = false;
		for (var i=0; i<DeliveryCount; i++){
			var isDisabled = false;
			Debugln('checking method '+deliveryItems[i].Name);
			if (ByPayment) {
				isDisabled = isDeliveryPaymentDisabled( deliveryItems[i].MethodID, SelPaymentMethodID );
			}
			var el = document.getElementById('radioDeliveryMethodID_'+deliveryItems[i].MethodID);
			if (el){
			    el.disabled = isDisabled;
			    el.setAttribute('disabled', isDisabled);
				if (isDisabled && el.checked){
					el.checked = false;
					selectedDisabled = true;
				}
				if (!isDisabled && (firstEnabled == null)){
					firstEnabled = el;
				}
			}
		}
		if (selectedDisabled){
			firstEnabled.checked = true;
			SelDeliveryMethodID = firstEnabled.value;
			recalcAfterDeliveryChanged();	
		}
	}
}

function RefillPaymentSelection(ByPayment){
	DebuglnB('RefillPaymentSelection(ByPayment='+ByPayment+')');
	var select = document.getElementById('comboPaymentMethodID');
	var newSelIndex = -1;
	if (select){
		for (var i = select.options.length - 1; i >= 0; i--){
    		select.options[i] = null;
    	}
    	var k = 0;
		for (var i=0; i<PaymentCount; i++){
			var isDisabled = false;
			if (ByPayment){
				isDisabled = isDeliveryPaymentDisabled( SelDeliveryMethodID, paymentItems[i].MethodID);
			}
			if (!isDisabled){
				select.options[k] = new Option( paymentItems[i].Name, paymentItems[i].MethodID);
				if (SelPaymentMethodID == paymentItems[i].MethodID){
					newSelIndex = k;
				}
				k++;
			}
			
		}
		if (newSelIndex != -1){
			// mark last selected value as selected in rebuit list
			select.options[newSelIndex].selected = true;
		}else{
			// mark first as new selected payment
			if (k>0){
				select.options[0].selected = true;
				SelPaymentMethodID = select.options[0].value;
				recalcAfterPaymentChanged();				
			}
		}
	}else{
	
		// pro pripad zobrazeni vyberu druhu plateb radio buttonama se disabluji nepovolene platby
    	var k = 0;
    	var firstEnabled = null;
    	var selectedDisabled = false;
    	Debugln('..listuji vsechny platby, pocet='+PaymentCount);
		for (var i=0; i<PaymentCount; i++){
			var isDisabled = false;
			Debugln('checking method '+paymentItems[i].MethodID);
			if (ByPayment) {
				isDisabled = isDeliveryPaymentDisabled( SelDeliveryMethodID, paymentItems[i].MethodID );
			}
			var el = document.getElementById('radioPaymentMethodID_'+paymentItems[i].MethodID);
			Debugln('..el='+el);
			if (el){
					Debugln('..was Disabled='+el.disabled+', isDisabled='+isDisabled);
				if (el.disabled && !isDisabled){
					Debugln('..povoluji zakazane pole');
				}
			    el.disabled = isDisabled;
			    //el.setAttribute('disabled', isDisabled);
				if (isDisabled && el.checked){
					el.checked = false;
					selectedDisabled = true;
				}
				if (!isDisabled && (firstEnabled == null)){
					firstEnabled = el;
				}
			}
		}
		if (selectedDisabled){
			firstEnabled.checked = true;
			SelPaymentMethodID = firstEnabled.value;
			recalcAfterPaymentChanged();	
		}
	}

}


// example of DisabledDeliveryPayments
 

//var DisabledDeliveryPayments = new Array( DeliveryCount );  
//DisabledDeliveryPayments[0] = new Array( 1, 2, 3);  // first item is DeliveryMethodID, next items are disabled payment methods
//DisabledDeliveryPayments[1] = new Array( 2, 3);
//DisabledDeliveryPayments[2] = new Array( 3, 0);

 
function isDeliveryPaymentDisabled(DeliveryID, PaymentID){
	for (var i=0; i < DisabledDeliveryPayments.length; i++){
		var DisabledPayments = DisabledDeliveryPayments[i];  // first item in array is DeliveryMethodID
		var CheckedMethodID = DisabledPayments[0];
		// alert('CheckedID = '+CheckedMethodID);
		if (DisabledPayments[0] == DeliveryID){
		
			for (var j=1;  j < DisabledPayments.length; j++){
				if (DisabledPayments[j] == PaymentID){
					return true;
				}
			}
		}
	}
	return false;
}