var language;

function cartInit(){
	$('orderButton').onclick = gotoOrder;
	$('updateButton').onclick = calculate;
	
	var deleteButtons = $$('.deleteButton');
	
	for(var i = 0; i < deleteButtons.length; i++){
		deleteButtons[i].onclick = deleteItem;
	}
}

function deleteItem(){
	if(language == "TR"){
		if(!confirm("Bu ürünü sepetten kaldırmak istediğinizden emin misiniz?")) return;
	}else if(language == "EN"){
		if(!confirm("Are you sure you want to delete this item from the cart?")) return;
	}
	var index = this.id.split("-")[1];
	var postVars = "index="+index;
	var opt = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postVars,
		// Handle successful response
		onSuccess: function(t) {
			//calculate();
			window.location.reload();
		},
		onFailure: function(t) {
			if(language == "TR"){
				alert("İşlem sırasında bir hata oluşmuştur, lütfen tekrar deneyiniz.");
			}else if(language == "EN"){
				alert(" problem occured during the operation, please try again later.");
			}
		},
		on404: function(t) {
			alert("404");
		}
	}
	
	new Ajax.Request('/ajax/delete_item.php', opt);
}

function gotoOrder(){
	if($('couponCode').value != ""){
		window.location = $('orderURL').value+"?fromCart=1&coupon="+$('couponCode').value;
	}else{
		window.location = $('orderURL').value+"?fromCart=1";
	}
}

function validate(){
	var itemCount = $('itemCount').value;
	for(var i = 0; i < itemCount; i++){
		if($("count-"+i).value == ""){
			if(language == "TR"){
				alert("Adet değerleri girilmelidir.");
			}else if(language == "EN"){
				alert("Please enter the quantity.");
			}
			return false;
		}else if($("count-"+i).value == "0"){
			if(language == "TR"){
				alert("Adet değerleri 0 olamaz.");
			}else if(language == "EN"){
				alert("The quantity cannot be zero.");
			}
			return false;
		}
	}
	return true;
}

function calculate(){
	
	if(!validate()) return false;
	
	var itemCount = $('itemCount').value;
	
	var postVars = "";
	for(var i = 0; i < itemCount; i++){
		postVars += "product-"+i+"="+$("product-"+i).value+"&";
		postVars += "color-"+i+"="+$("color-"+i).value+"&";
		postVars += "count-"+i+"="+$("count-"+i).value+"&";
	}
	
	postVars += "coupon="+$('couponCode').value+"&";
	postVars += "itemcount="+itemCount;
	
	var opt = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postVars,
		// Handle successful response
		onSuccess: function(t) {
			$('cart').innerHTML = t.responseText;
			cartInit();
			setTimeout(removeErrors,5000);
		},
		onFailure: function(t) {
			alert("Error");
		}
	}
	
	new Ajax.Request('/ajax/update_cart.php', opt);
}

function removeErrors(){
	var errors = $$(".error");
	for(var i = 0 ; i < errors.length; i++){
		Effect.Fade(errors[i]);
	}
}

addLoadEvent(cartInit);
