// AJAX functions for adding an item to the basket:

// First off, access all of the add to cart buttons on the product page:
$(document).ready(function() {
	
	var buttons = $('input.basketAdd');
	
	// Loop through the buttons and add everything:
	$('input.basketAdd').each(function() {
		// Get the product ID so we can get the form:
		var productId = parseInt($(this).attr('name').replace('submit_', ''));
		var formSelector = 'form#add_' + productId
		
		// Get the form element:
		var formElement = $(formSelector);
				
		// Get the other options:
		var src_category 	= $(formSelector + ' input[name="src_category"]').val();
		var src_subcategory = $(formSelector + ' input[name="src_subcategory"]').val();
		var src_search		= $(formSelector + ' input[name="src_search"]').val();
		var src_product		= $(formSelector + ' input[name="src_product"]').val();
		var productName  	= $('h2#product_name_' + productId).html();
		
		$(this).click(function() {
			// Get the quantity when they click in case it's changed:
			var quantity 		= $(formSelector + ' input[name="qty"]').val();
			var datarel = $(this).attr('data-rel');
			// Get the selected packsize:
			var packsize = $(formSelector + ' input[@name=packsize]:checked').val();
			// Get the weight text:
			var weightText = $('span#weight_text_' + packsize).html();
			
			// Check they want to add it:
			if(confirm('Add ' + quantity + ' x ' + weightText + ' x ' + productName + ' to basket?'))
			{
				// If any of the parameters are undefined, set them to '':
				if(src_category === undefined) 		src_category = '';
				if(src_subcategory === undefined) 	src_subcategory = '';
				if(src_search === undefined)		src_search = '';
				if(src_product === undefined)		src_product = '';
				
				// Now prepare the AJAX:
				$.ajax({
					type: "GET",
					url: "/add.php",
					data: "ajax=true&packsize=" + packsize + "&qty=" + quantity + "&src_category=" + src_category + "&src_subcategory=" + src_subcategory + "&src_product=" + src_product + "&src_search=" + src_search,				
					success: function() {
						// First, update the quantity in the cart link at the top of the page:
						var oldQuant = $('span#cartnumberproducts').html().replace('product', '');
						oldQuant = parseInt(oldQuant.replace('s', ''));
						
						// Add the new quantity:
						var newQuant = oldQuant + parseInt(quantity);
						(newQuant != 1) ? productString = 'item' : productString = 'items';
						
						// Update the span:
						$('span#cartnumberproducts').html(newQuant + ' ' + productString);
						alert(quantity + ' x ' + weightText + ' x ' + productName + ' added to your basket');
						
						// If the data-rel is set, we need to reload:
						if(datarel == 'inCart')
							window.location = '/basket/';
					}
				});
			}
		
			//Return false to prevent the form submitting:
			return false;
		});
	});
	
});
