$(document).ready(function(){

	$.ajaxSetup({cache: false});


	$('#EmptyBag').click( function() {
		$.ajax({
			url: '/shoppingbag/empty_bag',
			success: function() { window.location.reload() }
		});

		return false;
	});


	$('#UpdateQtys').click( function() {
		$.ajax({
			type: 'POST',
			url: '/shoppingbag/update_qtys',
			data: $('#bagForm').serialize(),
			success: function(response) {
				if( response == 'success' ) {
					alert('Bag quantities updated.');
					updateTotal();
				}
				else
					alert(response);
			}
		});

		//return false;
	});


	$('.remove').click( function() {
		
		if( confirm('Really remove this item from your bag?') ) {
			
			var productDiv = $(this).parent().parent();

			$.ajax({
				url: $(this).attr('href'),
				success: function(r) {
					 var splited = r.split('__');
					 
					if( splited[0] == 'success' ) {
						productDiv.fadeOut('slow');
						$('#BagCount').text( parseInt($('#BagCount').text()) - 1 );
						if( $('#BagCount').text() == 0 )
							$('#ShoppingBag').html('<p>There are no items in your shopping bag.</p>');

						updateTotal();
						updateShipping();
					}
					else
						alert(r);
				}
			});	

		}
				
		return false;
	});


	function updateShipping() {
		$.ajax({
			url: '/shoppingbag/add_shipping/true',
			success: function(r) {
				if( r == 'false' )
					$('#ShippingItem').fadeOut('slow');
			}
		});
	}
	

	function updateTotal() {
		$.ajax({
			url: '/shoppingbag/total',
			success: function(text) {
				$('#TotalAmount').text(text);
			}
		});
	}


});

