$(document).ready(function() { 
		
	var checkBasketOfferCode = $('.currentOfferCodeHidden').val();

	if(checkBasketOfferCode== undefined) {
		// Show the enter product code offer options
		$('.offerCodeLink').show();
	}
	else
	{
		// Remove the enter product code offer options
		$('.offerCodeLink').hide();
	}
	
	
	var checkProductOfferCode = $('.currentProductOfferCodeHidden').val();
	
	if(checkProductOfferCode == " ") {
		// Show the enter basket code offer
		$('#addBasketOfferCodeForm').show();
	}
	else
	{
		// Remove the enter basket code offer
		$('#addBasketOfferCodeForm').hide();
	}
	
	
	
	// Set-up any existing active offer codes.
	$('#cartList .currentOfferCode').each(function(i) {
		addRemovalEvent(this);
		$(this).siblings('.offerCodeLink').hide();
	});
	
	// Set-up an existing BASKET offer codes

	var currentBasketCode = $('#basketDiscountForm .currentOfferCode');
	if(currentBasketCode.length > 0) {
		// Remove the removal form
		$('#removeBasketOfferButton').click(function() {
			var offerCode = $(this).siblings('.currentOfferCodeHidden').val();
			removeBasketOffer(offerCode, this);
			return false;
		});
		$('#addBasketOfferCodeForm').hide(); // Hide the offer code form.
	}
	
	// Swaps the link for a form. Keeps it neat.
		
	$('.offerCodeForm').hide();
	
	$('.offerCodeLink').click(function() {
		$(this).hide();
		$(this).siblings('.offerCodeForm').show();
		return false;
	});
	
	$('.cancelOfferCode').click(function() {
		$(this).parent().hide();
		$(this).parent().siblings('.offerCodeLink').show();
		return false;
	});
	
	// Removes the value if its the default.
	
	var defaultOfferCodeValue = 'Offer code'; // Slightly hard-coded!
		
	$('.defaultValueInput').focus(function() {
		var currentValue = $(this).val();		
		if(currentValue == defaultOfferCodeValue) {
			$(this).val('');
		}	
		$('.defaultValueInput').blur(function() {
			if($(this).val() == '') {
				$(this).val(defaultOfferCodeValue);	
			}
		});		
	});
	
	// Submit button for applying a BASKET offer code.
	//////////////////////////////////////////////////
	$('#basketDiscountForm').submit(function() { return false; });
	$('#basketDiscountForm .basketDiscountSubmit').click(function() {
		var codeValue = $(this).siblings('#basketDiscountOfferCode').val();
		
		if(codeValue != null) {
			applyBasketOffer(codeValue, $(this));
		}
		return false;
	});
	
	
	
	// Submit button for applying a PRODUCT offer code
	//////////////////////////////////////////////////
	
	$('.offerCodeForm form').submit(function() { return false; });
	
	
	$('.offerCodeForm form .applyButton').bind("click", function() {
		
		//console.info("Apply button clicked...");
		
		var myForm = $(this).parent();
		var stylesTypesValue = myForm.children('.foreignId').val();
		var codeValue = $('#basketDiscountOfferCode').val();
		
		var dataString = ({"data[OfferCodeApplication][foreign_id]": stylesTypesValue, "data[OfferCode][code]": codeValue});
		
		$.ajax({
			type: "POST",
			url: "/basket/apply_product_offer/" + stylesTypesValue + '/' + codeValue,
			data: dataString,
			dataType: "json",
			success: function(response) {
				
				
				
				var offerCode = response.offerCode;
				
				if(offerCode.length == 0) {	
					
					// Code was not valid for this product.
					
					// showOfferError(myForm);	
					//console.info("This should be an apply button...");
					//console.debug($(this));
					
					
				}
				else {
					
					//console.info("Ok, this actually worked.");
					//console.debug(offerCode.code);
					
					// $('#addBasketOfferCodeForm').hide(); // Hide the offer code form.
					
					var offerCodeCode = offerCode.code;
					
					// Swap the entry form for a removal form.
					
					/*
					var removeFormHTML = '<input class="hackCurrentProductOfferCodeHidden" value="' + offerCodeCode + '" /><form method="post" class="HELLO"><input name="data[OfferCodeApplication][foreign_id]" class="foreignId" type="hidden" value="' + offerCode.foreign_id + '" /><input type="image" value="Remove code" class="button removeOfferButton" src="/img/remove_offer_code.jpg" style="margin-top: 5px;" /></form>';	
					var htmlString = '<div class="currentOfferCode"><strong>Offer code:</strong> ' + offerCodeCode + ' ' + removeFormHTML + '</div>';
						
					myForm.siblings('.cancelOfferCode').hide();
					myForm.hide();
					myForm.parent().prepend(htmlString);
					*/
					
					// Show the discount
					var oldPrice = ((offerCode.quantity * offerCode.orig_price) / 100).toFixed(2);
					var newPrice = ((offerCode.quantity * offerCode.discount_price) / 100).toFixed(2); 
						
					$('#basketItem' + stylesTypesValue + ' .discountPrice').replaceWith('<span class="discountPrice"><span class="disabledPrice">&pound;' + oldPrice + '</span> <span>&pound;' + newPrice + '</span>');
					
					// Notify the user of success.
					showOfferSuccess(myForm);
					
					//Update currentProductOfferCodeHidden with True
					$('#productOfferCode').append($('input.currentProductOfferCodeHidden').val('True'));
					
					// Apply an event to the removal form.
					var currentOfferCode = myForm.parent().children('.currentOfferCode');
					addRemovalEvent(currentOfferCode);
										
					// Update the totals	
					updateProductDiscountedTotals(response);
					
				}
				
			}
		});
		
		return false;
		
	});
	
	function addRemovalEvent(currentOfferCode) {
								
		var button = $(currentOfferCode).find('.removeOfferButton');
				
		button.click(function() {			  
			var removeOfferForm = $(this).parent();
			removeProductOffer(removeOfferForm);
			return false;
		});
		
	}
	
	function showOfferError(myForm) {
		
		myForm.parent().prepend('<div class="offerError">Sorry, this code was invalid.</div>');
		var offerError = myForm.parent().children('.offerError');
		
		offerError.hide();		
		offerError.fadeIn(500).animate({opacity: 1.0}, 3000, "linear", function() {
			offerError.animate({opacity: 0}, 500);
			offerError.slideUp(500, function() { $(this).remove(); });											
		})
			
	}
	
	function showOfferSuccess(myForm) {
		
		myForm.parent().prepend('<div class="offerSuccess">Code added successfully.</div>');
		var msg = myForm.parent().children('.offerSuccess');
		
		msg.hide();		
		msg.fadeIn(500).animate({opacity: 1.0}, 3000, "linear", function() {
			msg.animate({opacity: 0}, 500);
			msg.slideUp(500, function() { $(this).remove(); });											
		});
			
	}
		
	function removeProductOffer(removeOfferForm) {
				
		var foreignId 	= removeOfferForm.children('.foreignId').val();
			
		var codeValue 	= removeOfferForm.siblings('.currentProductOfferCodeHidden,.hackCurrentProductOfferCodeHidden').filter(":first").val(); 
		var dataString 	= ({"data[OfferCodeApplication][foreign_id]": foreignId, "data[OfferCode][code]": codeValue});

		$.ajax({
			type: "POST",
			url: "/basket/remove_product_offer/" + foreignId + '/' + codeValue,
			data: dataString,
			dataType: "json",
			success: function(response) {		
				
				var offerCode = response.offerCode;

				// console.info("Success on function removeProductOffer");
				
				var entryForm = removeOfferForm.parent().parent().children('form'); // Show the original entry form.

				// Reset the discount	
				var resetPrice = ((offerCode.quantity * offerCode.orig_price) / 100).toFixed(2);
				
				// Update the totals	
				removingProductDiscountedCode(response);
				
				$('#basketItem' + foreignId + ' .discountPrice').replaceWith('<span class="discountPrice"><span>&pound;' + resetPrice + '</span>');
				
				entryForm.parent().hide(); // Hide the parent, so even though we're reset its contents, this won't be apparent.
				entryForm.show(); // These are reset ready for when the user clicks the link again, so we rinse and repeat.
				entryForm.siblings('.cancelOfferCode').show();
				entryForm.parent().find('.offerCodeCode').attr('value', 'Offer code'); // Reset value
				entryForm.parent().siblings('.offerCodeLink').show(); // Show the link!
				
				location.reload(true);
				removeOfferForm.parent().remove(); // Remove the removal form.
				
			}
		});
		
	}
	
	/**
	 *
	 * Attempts to apply a basket offer code provided by the customer.
	 *
	 */
	
	function applyBasketOffer(offerCode, offerCodeButton) {
	
		// Get all the products currently being used on the page.
		var foreignIds = [];
		$('#cartList .foreignId').each(function() { foreignIds.push($(this).val()); });
		foreignIds = foreignIds.join(",");
	
		var dataString = ({
			"data[OfferCode][code]": offerCode,
			"data[OfferCodeApplication][foreign_ids]": foreignIds
		});
				
		$.ajax({
			type: "POST",
			dataType: "json",
			data: dataString,
			url: "/basket/apply_combined_offer",
			success: function(response) {	  
				
				var offerCodeForm = offerCodeButton.parent('form');	  
	
				if(response == false) {
					onBasketOfferError(offerCodeForm, response);				
				}
				else {
					
					//Hide product offer codes option
					$('.offerCodeLink').hide();
					onBasketOfferSuccess(offerCodeForm, response);	
				}	  
			}
		});
		
		
	}
	
	/**
	 *
	 * No active basket offer code was found for the customer's provided code.
	 *
	 */
	
	function onBasketOfferError(myForm, response) {
				
		showOfferError(myForm);
	}
	
	/**
	 *
	 * A basket offer code was found for the provided code.
	 *
	 */
	
	function onBasketOfferSuccess(myForm, response) {
		
		updateDiscountedTotals(response); // Update the totals
		insertRemoveBasketCodeHTML(response.OfferCode.code, myForm);
		$('#addBasketOfferCodeForm').hide(); // Hide the offer code form.
		showOfferSuccess(myForm); // Show a little message
		$('#basketDiscountOfferCode').attr('value', ''); // Clear the text input value.
		
		// Remove the removal form
		$('#removeBasketOfferButton').parent("form").submit(function() { return false; });
		$('#removeBasketOfferButton').click(function() {
			var offerCode = response.OfferCode.code;
			removeBasketOffer(offerCode, this);
			return false;
		});
		
	}
	
	
	/**
	 *
	 * Shows the user the totals when the offer code on the products have been removed
	 *
	 */
	
	function updateProductDiscountedTotals(response) {
		
		//console.info("Updating product discounting totals.");
		var currentAmount = $('.currentDiscountAmount').val();
		
		var calculateSaving = ((response.Basket.beforeTotal - response.Basket.total) / 100);
		calculateSaving = calculateSaving * 100;
		currentAmount = currentAmount * 100;
		totalSaving = ((calculateSaving + currentAmount) / 100);

		totalSaving = totalSaving.toFixed(2);
		
		$('#sv .amount').text(totalSaving);
		$('#sv .discountAmount').append($('input.currentDiscountAmount').val(totalSaving));

		// JAC removed parseInt() due to its inability to handle decimal points e.g 127.50
		var purchaseTotal = (response.Basket.total / 100);
		purchaseTotal = purchaseTotal.toFixed(2);
		$('#pT .amount').text(purchaseTotal);
	}
	
	
	/**
	 *
	 * Shows the user that the totals have been updated, and reflect their offer code.
	 *
	 */
	
	function updateDiscountedTotals(response) {
		
		//console.info("Updating discounting totals.");
			
		// JAC removed parseInt() due to its inability to handle decimal points e.g 2.50
		var totalSaving = ((response.Basket.beforeTotal - response.Basket.total) / 100);
		totalSaving = totalSaving.toFixed(2);		
		
		//console.info("Before Total: "+response.Basket.beforeTotal);
		//console.info("Total: "+response.Basket.total);
		//console.info("Saving: "+totalSaving);

		$('#sv .amount').text(totalSaving);

		// JAC removed parseInt() due to its inability to handle decimal points e.g 127.50
		var purchaseTotal = (response.Basket.total / 100);
		purchaseTotal = purchaseTotal.toFixed(2);
		$('#pT .amount').text(purchaseTotal);	
		
	}
	
	
	/**
	 *
	 * Shows the user the totals when the offer code on the products have been removed
	 *
	 */
	
	function removingProductDiscountedCode(response) {
		
		//console.debug(response);
		
		//console.info("Resetting product discounting totals.");
		var currentAmount = $('.currentDiscountAmount').val();

		currentAmount = currentAmount * 100;
		
		// JAC removed parseInt() due to its inability to handle decimal points e.g 2.50
		var totalSaving = ((currentAmount - response.Basket.discounted_total) / 100);
		totalSaving = totalSaving.toFixed(2);
		
		//console.info("currentAmount: "+currentAmount);
		//console.info("Discount Total: "+response.Basket.discounted_total);
		//console.info("Before Total: "+response.Basket.beforeTotal);
		//console.info("Total: "+response.Basket.total);
		//console.info("Saving: "+totalSaving);
		
		
		$('#sv .amount').text(totalSaving);
		$('#sv .discountAmount').append($('input.currentDiscountAmount').val(totalSaving));
		
		var purchaseTotal = response.Basket.total / 100;
		purchaseTotal = purchaseTotal.toFixed(2);
		$('#pT .amount').text(purchaseTotal);
	}
	
	
	/**
	 *
	 * Shows the user the totals when the offer code has been removed
	 *
	 */
	
	function removingDiscountedCode(response) {
		
		// console.info("Resetting discounting totals.");

		// JAC removed parseInt() due to its inability to handle decimal points e.g 2.50
		var totalSaving = response.Basket.discounted_total;
		totalSaving = totalSaving.toFixed(2);
		
		
		$('#sv .amount').text(totalSaving);
		var purchaseTotal =  response.Basket.beforeTotal / 100;
		purchaseTotal = purchaseTotal.toFixed(2);
		$('#pT .amount').text(purchaseTotal);
	}
	
	/**
	 *
	 * Insert a bit of HTML that allows the user to remove their active basket code.
	 *
	 */
		
	function insertRemoveBasketCodeHTML(basketOfferCode, myForm) {
		var removeFormHTML = '<form method="post"><input name="data[OfferCode][code]" class="currentOfferCodeHidden" type="hidden" value="' + basketOfferCode + '" /><input type="image" value="Remove code" id="removeBasketOfferButton" class="button" src="/img/remove_offer_code.jpg" style="margin-top: 5px;" /></form>';	
		var htmlString = '<div class="currentOfferCode"><strong>Offer code:</strong> ' + basketOfferCode + ' ' + removeFormHTML + '</div>';
		$(myForm).parent().prepend(htmlString);
	}
	
	/**
	 *
	 * Remove a basket offer code via AJAX.
	 *
	 */

	function removeBasketOffer(offerCode, basketOfferButton) {
	
		// Get all the products currently being used on the page.
		var foreignIds = [];
		$('#cartList .foreignId').each(function() { foreignIds.push($(this).val()); });
		foreignIds = foreignIds.join(",");
	
		var dataString = ({'data[OfferCode][code]': offerCode, 'data[OfferCodeApplication][foreign_ids]' : foreignIds});
	
		$.ajax({
			url: "/basket/remove_combined_offer",
			type: "POST",
			dataType: "json",
			data: dataString,
			success: function(response) {
				
				//console.debug("AJAX Success.");
				
				//JAC created new function removingDiscountedCode
				removingDiscountedCode(response);  // Refresh the totals
				
				if(response.Basket.basketDiscount == 'true') {
					updateProductDiscountedTotals(response);	
				}
				
				$(basketOfferButton).parent().parent().remove(); // Remove the form
				$('#addBasketOfferCodeForm').show(); // Show the adding form again.	
				$('.offerCodeLink').show();
				
				//console.debug("Still here.");
				
			}			   
		});
		
	}
		
			   
});
