$('document').ready(function() {
	$('.buy').each(function() {
		$(this).bind('click', function() {
			var data = {
				id : $(this).attr('id')
			};
			var args = {
				type : "POST",
				url : "/add-to-cart/",
				data : data,
				success : function(datas) {
					$('#cart').fadeOut('slow', function() {
						$('#cart').html(datas);
					});
					$('#cart').fadeIn('slow');
				},
				error : function(err, err1) {
					alert('Упс, поломочка! Попробуйте попозже...1')
				}
			};
			$.ajax(args);
		});
	});
	$('.delete-from-cart').each(function() {
		$(this).bind('click', function() {
			id = $(this).parent().attr('ref')
			var data = {
				id : id
			};
			var args = {
				type : "POST",
				url : "/delete-to-cart/",
				data : data,
				success : function(data) {
					if (data == 'False') {
						document.location = "/mycart/";
					} else {
						$('.' + id).each(function() {
							$(this).remove();
						});
						$('#total').html(data);
						update_cart_header();
					}
				},
				error : function(err, err1) {
					alert('Упс, поломочка! Попробуйте попозже...2')
				}
			};
			$.ajax(args);
		});
	});
});

function update_cart_header() {
	$.ajax( {
		url : '/show-to-cart/',
		success : function(data) {
			$('#cart').html(data);
		},
		error : function(err) {
			alert('Упс, поломочка! Попробуйте попозже...3')
		}
	});
}
