/**
 * Remove the selected product from the cart.
 * 
 * @param productCode The unique product code of the product to remove from the cart.
 */
function removeFromCart( productCode ) {
	if ( productCode ) {
		$.ajax({
			type: 'POST',
			url: "/removeFromBasket.action",
			data: { productCode: productCode },
			success: function(data) {
				if( data.successful ) {
					// remove all the elements that need removal when this product goes out of cart
					$( '.removeOnDelete_' + productCode ).remove();
					if (data.lines == ''){
						$('#shoppingCart').hide();
						$('#shoppingCartEmpty').show();
					}
				} else {
					alert( data.errorMessage );
				}
				
				// and update the shopping cart information after this operation
				updateShoppingBasketAfterOperation( data, false );				
			},
			error: function(xmlHttpRequest, textStatus, errorThrown) {
				alert( Translations['unableToRemoveFromCart'] );
			},
			dataType: 'json'
		});
	}
}

/**
 * Update the specified product in the cart with the provided quantity.
 * 
 * @param productCode The unique reference to the product to update
 * @param quantity The new quantity of the product in the basket
 */
function updateCart( productCode, quantity ) {
	// make sure a valid input parameter has been specified
	if ( productCode ) {
		$.ajax({
			url: '/updateBasket.action',
			type: 'POST',
			contentType: "application/json",
			dataType: 'json',
			data: JSON.stringify({ productCode: productCode, quantity: quantity }),
			success: function(data) {
				if( !data.successful ) {
					alert( data.errorMessage );
				}
				
				// and update the shopping cart information after this operation
				updateShoppingBasketAfterOperation( data, false );
				
				// and swith the 'error' bar for this product quantity if needed
				for (var i = 0; i < data.lines.length; i++) {
					// only handle the current product!
					if( data.lines[i].productCode == productCode ) {
						if( data.lines[i].quantityError ) {
							$( '.updateOnQuantityInvalid_' + productCode ).text( Translations['invalidQuantity'] );
						} else {
							$( '.updateOnQuantityInvalid_' + productCode ).text( "" );
						}
					}
				}
			},
			error: function(xmlHttpRequest, textStatus, errorThrown) {
				alert( Translations['unableToUpdateCart'] );
			}
		});
	}
}

/**
 * Select/deselect the gift wrap in the shopping basket.
 * 
 * @param productCode The unique reference to the product to update
 * @param giftWrap Whether or not the gift wrap is requested
 */
function updateGiftWrap( productCode, giftWrap ) {
	// make sure a valid input parameter has been specified
	if ( productCode ) {
		$.ajax({
			url: '/updateGiftWrap.action',
			type: 'POST',
			contentType: "application/json",
			dataType: 'json',
			data: JSON.stringify({ productCode: productCode, giftWrap: giftWrap }),
			success: function(data) {
				if( !data.successful ) {
					alert( data.errorMessage );
				}
				
				// and update the shopping cart information after this operation
				updateShoppingBasketAfterOperation( data, false );				
			},
			error: function(xmlHttpRequest, textStatus, errorThrown) {
				alert( Translations['unableToUpdateGiftWrap'] );
			}
		});
	}
}

/**
 * When an AJAX call is performed on the shopping basket, this method will update the
 * view with the correct values.
 * 
 * @param operationResult The resulting object from the AJAX operation on the basket
 * @param updateQuantities Whether or not to update the quantities.
 */
function updateShoppingBasketAfterOperation( operationResult, updateQuantities ) {
	// update the total price
	$( '.updateOnCartPriceUpdate' ).text( operationResult.totalPrice );
	
	// update the prices to be shown without the delivery cost
	$( '.updateOnCartPriceWithoutDeliveryCostUpdate' ).text( operationResult.totalPriceWithoutDeliveryCost );
	
	// update the subtotal
	$( '.updateOnCartSubtotalUpdate' ).text( operationResult.subtotal );
	
	// update the number of products currently in the basket
	$( '.updateOnCartNumberEntries' ).text( operationResult.totalQuantityInBasket );
	
	// update the loyalty points
	$( '.loyaltyPointsForOrder' ).text( operationResult.loyaltyPoints )
	
	// the delivery cost
	$( '.updateOnCartDeliveryCostUpdate' ).text( operationResult.deliveryCost );
	
	// update the rows
	for (var i = 0; i < operationResult.lines.length; i++) {
		// update all the quantities
		var productCode = operationResult.lines[i].productCode;
		
		$( '.updateOnQuantity_' + productCode ).text( operationResult.lines[i].quantity );
//		if( updateQuantities ) {
//			$( ":input[name=updateOnQuantity_" + productCode ).val( operationResult.lines[i].quantity );
//		}
		
		// and the price
		$( '.updateOnPrice_' + productCode ).text( operationResult.lines[i].price );
	}
}
