$(document).ready(function(){
	$('.del-comm-button').click(function(){ return removeCart($(this)); });
	$("input[name='agreement']").change(function(){ isValidForNextStep($('tfoot .sum').html()); });
	isValidForNextStep($('tfoot .sum').html());
 });

function removeCart(button)
{
	var url = button.parent().attr('action') + '/format/json';
	$('#loading-cart').show();
	
	$.ajax({
		async: true,
		type: 'POST',
		url: url, 
		dataType: 'json',
		data: {id: button.prev().prev().val(), count: button.prev().val()}, 
		success: function(data) {
			var evalData = eval(data);
			if (evalData.status <= 0) 
				alert('Shopping Cart is not updated.');
			else {
				var totalPrc = button.parent().parent().prev();
				var price = totalPrc.prev();
				var amount = price.prev();
				var totalPrice = evalData.totalPrice;
				isValidForNextStep(totalPrice);
				$('#cart-ref').replaceWith(evalData.response);
				if(totalPrice == 0) totalPrice = '0.0';
				$('#content tfoot .sum').html(totalPrice);
				
				var count = (amount.html()) - 1;
				if (count > 0) {
					amount.html(count);
					totalPrc.html(count * priceToFloat(price.html()));
				}
				else button.parent().parent().parent().hide();
			}
		},
		error: function() {
			alert('Error: AJAX failed!');
		},
		complete: function() {
			$('#loading-cart').hide();
		}
		
	});
	return false;
}

function isValidForNextStep(totalPrice)
{
	totalPrice = priceToFloat(totalPrice);
	
	if (totalPrice <= 0 || $("input[name='agreement']").attr('checked') != true) {
		$("input[name='next']").attr('disabled', 'disabled');
	}
	else {
		$("input[name='next']").removeAttr('disabled');
	}
}

function priceToFloat(price)
{
	if (typeof price == "string") {
		price = price.replace(/\s+/,'');
		price = price.replace(/,/,'.');
		price = parseFloat(price);
	}
	
	return price;
}
