/* VALIDATE FUNCTIONS */

var paymentDisabled = [];
var paymentDisabledInit = false;

function checkCartOptions(form)
{
	if (form["shipping_code"] && !checkRadio(form, "shipping_code", "Prosz\u0119 wybra\u0107 form\u0119 wysy\u0142ki", "shipping_code_1")) return false;
	return checkRadio(form, "payment_code", "Prosz\u0119 wybra\u0107 spos\u00f3b p\u0142atno\u015bci", "payment_code_1");
}

function checkAddressData(form)
{
	// 1st part
	var status = checkInput("ship_first_name","Podaj Imi\u0119") &&
	checkInput("ship_last_name","Podaj Nazwisko")
	if(!status) return false;

//	if (typeof orderShippingCode!="undefined" && orderShippingCode != 'kraj:odbior_salon')
//	{
		status = checkInput("ship_address","Podaj Ulica") &&
		checkInput("ship_address2","Podaj Numer Domu") &&
		checkInput("ship_city","Podaj Miasto") &&
		checkInput("ship_zip","Podaj Kod Pocztowy");
		// checkPostCode("ship_zip","Podaj prawidłowy Kod Pocztowy\n(Dwie cyfry, myślnik, Trzy cyfry)");
		if(!status) return false;
//	}
	// check pesel T#3177,fwo 2007-09-21, zakomentowanie sprawdzania numeru
	//T#10019 if($JM("mil_pesel") && !checkInput("mil_pesel","Podaj prawid\u0142owy numer PESEL")) return false;
	 //checkPESEL("mil_pesel","Podaj prawid\u0142owy numer PESEL")) return false;

	if (typeof orderShippingCode!="undefined" && orderShippingCode == 'kraj:odbior_salon'
		&& !checkInput("ship_phone","Podaj numer telefonu kontaktowego")) return false;
	if(!checkEmail("ship_email","Podaj prawid\u0142owy adres Email")) return false;

	// 2nd part
	if($JM("bill_vat").checked)
	{
		//status = checkRadio(form, "bill_vat_type","Prosz\u0119 wybra\u0107 rodzaj faktury", "bill_vat_type_1") &&
		status = checkInput("bill_first_name","Podaj nazw\u0119 firmy lub organizacji") &&
		checkInput("bill_last_name","Podaj NIP") &&
		checkInput("bill_address","Podaj ulic\u0119") &&
		checkInput("bill_address2","Podaj numer domu") &&
		checkInput("bill_city","Podaj miasto") &&
		checkInput("bill_zip","Podaj kod pocztowy");
		if(!status) return false;
	}

	if($JM("mil_agreement").type.toLowerCase()=="hidden") return true;
	return checkRadio(form, "mil_agreement","Prosz\u0119 wyrazi\u0107 zgod\u0119 na przetwarzanie danych osobowych", "mil_agreement");
}

function changeInvoiceStatus(input)
{
	var vatContainer = $JM("invoice_container");
	var inputs = vatContainer.getElementsByTagName("input");
	if(input.checked)
	{
		removeClass($JM("fill_data"),"fill_hidden");
		removeClass(vatContainer,"vat_hidden");
	}
	else
	{
		addClass($JM("fill_data"),"fill_hidden");
		addClass(vatContainer,"vat_hidden");
	}
	for( var i = 0; i < inputs.length; i++ )
		if(inputs[i] != input)
		{
			if(input.checked) removeClass(inputs[i],"disabled");
			else addClass(inputs[i],"disabled");
			inputs[i].disabled = !input.checked;
		}
}

function copyAddressData()
{
	//if(confirm("Czy skopiowa\u0107 tak\u017Ce imi\u0119 i nazwisko?"))
	$JM("bill_first_name").value = $JM("ship_first_name").value + " " + $JM("ship_last_name").value;
	$JM("bill_address").value = $JM("ship_address").value;
	$JM("bill_address2").value = $JM("ship_address2").value;
	$JM("bill_city").value = $JM("ship_city").value;
	$JM("bill_zip").value = $JM("ship_zip").value;
}

/* RENDER FUNCTIONS */
function toolTip()
{
	var divCollection = document.getElementsByTagName("div");

	for( var i = 0; i < divCollection.length; i++ )
	{
		if( divCollection[i].className.indexOf("tooltip") != -1 )
		{
			divCollection[i].onmouseover = function() {	addClass(this,"hover"); this.parentNode.style.zIndex = 1; }
			divCollection[i].onmouseout = function() { removeClass(this,"hover"); this.parentNode.style.zIndex = 0; }
		}
	}
}

function hoverOptions()
{
	var optionsUl = document.getElementsByTagName("ul");

	for( var i = 0; i < optionsUl.length; i++ )
	{
		if( optionsUl[i].className.indexOf("checkout_options") != -1 )
		{
			var options = optionsUl[i].getElementsByTagName("li");
			for(var j = 0; j < options.length; j++)
			{
				options[j].onmouseover = function() { addClass(this,"hover");	}
				options[j].onmouseout = function() { removeClass(this,"hover"); }
			}
		}
	}
}

function updateOptions()
{
	var total = $JM("total_price");

	if(!total) return;

	var totalTop = $JM("total_top");
	var base = $JM("base_price");
	var discount = $JM("discount_price");
	var steps = $JM("checkout_steps");
	var billShipMain = $JM("bill_ship_price_main");
	var billShipTotal = $JM("bill_ship_price_total");
	var stepsContent = "<li class=\"first_child past\"><span>1. </span>Koszyk</li><li class=\"after_active\"><span>2. </span>Twoje Dane</li><li><span>3. </span>Podsumowanie</li>";
	//steps.innerHTML;

	var basePrice = base.innerHTML.replace(",",".");
	basePrice = parseFloat(basePrice);
	var discountPrice = (discount) ? discount.innerHTML.replace(",",".") : 0;
	discountPrice = parseFloat(discountPrice);

	updateRender($JM("payment_options"));
	updateRender($JM("shipping_options"));

	this.preUpdatePrices = function() { updatePrices(); }

	function updateRender(container)
	{
		var options = container.getElementsByTagName("input");
		for(var i = 0; i < options.length; i++)
		{
			options[i].onclick = function()
			{
				if( this.id.slice(0,8) == "shipping" )
					changePaymentTypes(this);

				updatePrices(this);
			}
		}
	}

	// when discount value is greater then order value

	function updatePrices(option)
	{
		// logic

		var paymentPrice = parseFloat(getPrice($JM("payment_options")));
		var shippingPrice = parseFloat(getPrice($JM("shipping_options")));
		var discountPrice = (discount) ? discount.innerHTML.replace(",",".") : 0;
		discountPrice = parseFloat(discountPrice);
		var totalPrice =  discountPrice + paymentPrice + shippingPrice;

		// bill & ship price
		try {
			if (billShipFree) {
				billShipMain.innerHTML = formatPrice(0,2);
				billShipTotal.innerHTML = formatPrice(0,2);
				// total price
				total.innerHTML = formatPrice(0,2);
				totalPrice = 0;
			}
			else
			{
				billShipMain.innerHTML = formatPrice(paymentPrice + shippingPrice,2);
				billShipTotal.innerHTML = formatPrice(paymentPrice + shippingPrice,2);
				// total price
				total.innerHTML = formatPrice(totalPrice,2);
			}
		} catch(e){
			if (billShipMain)
			{
				billShipMain.innerHTML = formatPrice(paymentPrice + shippingPrice,2);
			}
			if (billShipTotal)
			{
				billShipTotal.innerHTML = formatPrice(paymentPrice + shippingPrice,2);
			}
			// total price
			if (total)
			{
				total.innerHTML = formatPrice(totalPrice,2);
			}
		}

		if (totalPrice == 0)
		{
			paymentPrice = 0;
			shippingPrice = 0;
		}
		if (discountPrice != null)
		{

			total.innerHTML = formatPrice(discountPrice + paymentPrice + shippingPrice	,2);
		}

		// total top price
		if(totalTop) totalTop.innerHTML = total.innerHTML + " PLN";

		//update steps
		if(container.id == "payment_options") updateSteps(this);

		// installments
		if(option && option.value.indexOf("instalments:") != -1)
			updateInstallments(option);
	}

	function getPrice(container)
	{
		var options = container.getElementsByTagName("input");
		for(var i = 0; i < options.length; i++)
			if(options[i].checked)
				return options[i].parentNode.parentNode.parentNode.getElementsByTagName("span").item(2).innerHTML.slice(0,-17).replace(",",".");;
		return 0;
	}

	function updateSteps(elem)
	{
		var code = elem.title;
		if(code.slice(0,12) == "platnoscipl:") setStepMode(1);
		else setStepMode(2);
	}

	function setStepMode(mode)
	{

		var lastSteps = (mode == 1) ? "<li><span>4. </span>P\u0142atno\u015B\u0107</li><li class=\"last_child\"><span>5. </span>Potwierdzenie</li>" :
			"<li class=\"last_child\"><span>4. </span>Potwierdzenie</li>";
		steps.innerHTML = stepsContent + lastSteps;
	}

}

function changeShopReceiptShipping(select)
{
	var input = select.parentNode.parentNode.getElementsByTagName("input")[0];
	var label = select.parentNode.parentNode.getElementsByTagName("label")[0];
	var price = select.parentNode.parentNode.parentNode.getElementsByTagName("span")[2];

//	var values = select.value.split("_");
//	var id = values[1];
//	var code = values[0];
//
//	input.id = "shipping_code_" + id;
//	input.value = code;
//	label.htmlFor = input.id;
	price.innerHTML = select.options[select.selectedIndex].title + "<span>PLN</span>";
	input.checked = true;
	input.onclick();
}

function changeForeignShipping(select)
{
	var input = select.parentNode.parentNode.getElementsByTagName("input")[0];
	var label = select.parentNode.parentNode.getElementsByTagName("label")[0];
	var price = select.parentNode.parentNode.parentNode.getElementsByTagName("span")[2];

	var values = select.value.split("_");
	var id = values[1];
	var code = values[0];

	input.id = "shipping_code_" + id;
	input.value = code;
	label.htmlFor = input.id;
	price.innerHTML = select.options[select.selectedIndex].title + "<span>PLN</span>";
	input.checked = true;
	input.onclick();
}

function __contains(a, obj){
	  for(var i = 0; i < a.length; i++) {
	    if(a[i] === obj){
	      return true;
	    }
	  }
	  return false;
	}


function changePaymentTypes(shippingOption)
{
	initPaymentDisabledId();

	if(!shippingOption.checked) return;

	var shippingOptionId = shippingOption.id.slice(shippingOption.id.lastIndexOf("_")+1);
	var paymentTypes = $JM("payment_options").getElementsByTagName("input");
	var checked = true;

	for(i = 0; i < paymentTypes.length; i++ )
	{
		if ( !__contains(paymentDisabled, paymentTypes[i].id) )
		{
			var option = paymentTypes[i].parentNode.parentNode;
			var iSelects = option.getElementsByTagName("select");
			var installmentOptions = iSelects.length == 1 ? iSelects[0] : null;

			if(shipping2PaymentConnections[shippingOptionId] && shipping2PaymentConnections[shippingOptionId][ paymentTypes[i].id.slice(paymentTypes[i].id.lastIndexOf("_")+1) ])
			{
				paymentTypes[i].disabled = false;
				if(installmentOptions) installmentOptions.disabled = false;
				removeClass(option,"disabled");
			}
			else
			{
				if(paymentTypes[i].checked) checked = false;
				paymentTypes[i].disabled = true;
				if(installmentOptions) installmentOptions.disabled = true;
				addClass(option,"disabled");
			}
		}
	}
	if(!checked)
		for(i = 0; i < paymentTypes.length; i++ )
			if(!paymentTypes[i].disabled) { paymentTypes[i].checked = true; break; }
}

function showHideDescription(button, e)
{
	e = e||window.event;
	var desc = button.parentNode.parentNode.parentNode.getElementsByTagName("p")[0];
	if(!containsClass(desc,"visible")) { addClass(desc,"visible"); addClass(button,"minus"); }
	else { removeClass(desc,"visible"); removeClass(button,"minus"); }
	if(e)
	{
		e.cancelBubble = true;
		if (e.preventDefault) e.preventDefault();
		e.returnValue = false;
	}
	return false;
}

function updateInstallments(option)
{
	var selectOption = option.parentNode.parentNode.getElementsByTagName("select")[0];
	var selected = selectOption.options[selectOption.selectedIndex];
	var tmp = selected.title.slice(6);
	tmp = tmp.split("/");
	var quantity = tmp[0];
	var percent = tmp[1];
	var total = parseFloat($JM("total_price").innerHTML.replace(",","."));
	var instalment = formatPrice( (total*(1+(percent/100)))  / quantity );

	var info = selectOption.parentNode.getElementsByTagName("div")[0];
	info.innerHTML = "<p><strong>Ilo\u015B\u0107 rat:</strong> "
				+ quantity + "</p><p class='last'><strong>Przybli\u017Cona wysoko\u015B\u0107 raty:</strong> "
				+ instalment + " z\u0142/m-c</p>";

}

function formatPrice(d,decimal)
{
	var d2 = Math.floor(d);
	var s = "" + ((d*10000-d2*10000));
	if (s.length>2) s=s.substr(0,2);
	else while (s.length<2) s="0"+s;

	var s1=""+d2;
	//if (s1.length>3) s1=s1.substr(0,s1.length-3) + "." + s1.substr(s1.length-3,s1.length)
	return s1+","+s;
}

function alertErros()
{
	var errorList = document.getElementById("error_list");
	if(!errorList) return;
	var msgErr = new String();

	var msgs = errorList.getElementsByTagName("li");
	for( var i = 0; i < msgs.length; i++ )
	{
		msgErr += msgs[i].innerHTML;
		if(i < msgs.length - 1) msgErr += ",<br>";
	}
	myAlert(msgErr);
}

/* LOGIC */

function updateProductsInCart(button)
{
	if(!checkProductsToDelete())
	{
		if (button.form.moveToWish.checked) myAlert("Wybierz produkty do przeniesienia!");
		else myAlert("Wybierz produkty do usuni\u0119cia!");
		return false;
	}

	if (button.form.moveToWish.checked)
	{
		button.form.action = "/sklep/lista_zyczen.xml";
		button.form.event.value='moveToWish'
	}
	else
	{
		button.form.action = "/sklep/koszyk.xml";
		button.form.event.value='remove';
	}
	button.form.submit();
	return false;

	function checkProductsToDelete()
	{
		var table = document.getElementById("product_table");
		var inputs = table.getElementsByTagName("input");
		for( var i = 0; i < inputs.length; i++ )
			if(inputs[i].className.indexOf("mark_delete") != -1 && inputs[i].checked)
				return true;
		return false;
	}
}

function serviceProductCount()
{
	var productTable = document.getElementById("product_table");
	if(!productTable) return;

	var updateButton = $JM("cart_product_recalculate");

	var productCounts = productTable.getElementsByTagName("tbody").item(0).getElementsByTagName("input");
	for( var i = 0; i < productCounts.length; i++ )
	{
		productCounts[i].onkeypress = function(e)
		{
			e=e||window.event;
			if(e.keyCode==13)
			{
				if(updateProductsCount(updateButton))
				updateButton.form.submit();
				return false;
			}
		}
	}
}

function serviceCouponCount()
{
	try
	{
		var input = $JM("coupon_code");
		input.onkeypress = function(e)
		{
			e=e||window.event;
			if(e.keyCode==13)
			{
				$JM("submit_cupon_code").onclick();
				return false;
			}
		}
	}
	catch(e) {	}
}

function updateProductsCount(button)
{
	var invalidInput = false;
	if(!checkPrices())
	{
		myAlert("Niepoprawna wartosc w polu Ilo\u015a\u0107", invalidInput);
		return false;
	}
	button.form.event.value='recalculate';
	button.form.submit();
	return false;

	function checkPrices()
	{
		var table = document.getElementById("product_table");
		var inputs = table.getElementsByTagName("input");
		for( var i = 0; i < inputs.length; i++ )
			if(inputs[i].className.indexOf("product_quantity") != -1)
			{
				var value = parseInt(inputs[i].value);
				if(isNaN(value) || value < 0) { invalidInput = inputs[i]; return false; }
			}
		return true;
	}
}

function onAddAddr(addr)
{
	if (!addr) return;
	$JM("ship_first_name").value = addr.firstName;
	$JM("ship_last_name").value = addr.lastName;
	$JM("ship_address").value = addr.address;
	$JM("ship_address2").value = addr.address2;
	$JM("ship_city").value = addr.city;
	$JM("ship_zip").value = addr.zip;
}

/* CHECKOUT CALCULATE OPTIONS */

function initPaymentDisabledId()
{
	//PCH, czy sa jakiekolwiek opcje? (pusty koszyk)
	var paymentOptions = $JM("payment_options");
	if ( !paymentDisabledInit && paymentOptions)
	{
		var paymentTypes = paymentOptions.getElementsByTagName("input");

		var ii = 0;
		for(i = 0; i < paymentTypes.length; i++ )
		{
			if ( paymentTypes[i].disabled )
			{
				paymentDisabled[ii++] = paymentTypes[i].id;
			}
		}
		paymentDisabledInit = true;
	}
}

function checkoutFunctions()
{
	initPaymentDisabledId();

	setTimeout(serviceProductCount,0);
	setTimeout(serviceCouponCount,0);
	setTimeout(alertErros,0);
	setTimeout(toolTip,0);
	setTimeout(hoverProducts,0);
	setTimeout(hoverOptions,0);
	var options = new updateOptions();

	if($JM("total_price"))
		options.preUpdatePrices();
}

function reportTradeDoubler(submitButton,orderId,affiliate)
{
	if(affiliate.slice(0,3) != "td:")
		return true;
	if($JM("td_report_container").getElementsByTagName("img")[0])
		return true;

	ajaxRequest("/sklep/tradedoubler_image.xml?id="+orderId, "GET", $JM("td_report_container"), function()
	{
		setTimeout(function(){ submitButton.form.submit(); },500);
	});

	return false;
}

function onCouponSubmit(button)
{
	if(!checkInput("coupon_code","Wprowad\u017a kupon aby m\u00f3c go u\u017cy\u0107!"))
		return false;

	button.form.event.value='recalculate';
	button.form.submit();
}

function onCouponDelete(button)
{
	$JM("coupon_code").value = '';
	button.form.event.value='recalculate';
	button.form.submit();
}

// moved to html addEvent(window,"load",checkoutFunctions);
