// Fields is given as a double-colon-separated list of field names whos 
	//  values we want for the given published or unpublished docID
	function getInfoFromMODx(docID, fields, published) {
		var result = "";
		$.ajax({
			url:'assets/templates/shoppingCart/modxHandler.php',
			type:'POST',
			async:false,
			data:{
				'docID':docID,
				'fields':fields,
				'published':published
			},
			success:function(r) { result = r; }
		});
		return result;
	}

	// JS wrappers for PHP files of the same name.  
	//
	function connTiedDBSelect(tableName, uniqueID, instance, fieldNames) {
		// Get an array of values from the conn-tied DB on this server for the given table and field names
		cartResultBits=[];
		$.ajax({
			url:'assets/templates/shoppingCart/connTiedDBSelect.php',
			type:'POST',
			async:false,
			data: {
				"table_name":tableName,
				"uniqueField":uniqueID,
				"instance":instance,
				"fields":fieldNames    // Field names are "::"-separated.
			},
			success:function(r) {
				cartResultBits = r.split("::");
			}
		});
		return cartResultBits;
	}
	
	// Get the availability for a given size, or just return the whole availability if no sizes
	function CheckForSizingQuantities(availableQuantity, docID, requiredSize) {
		var bits = availableQuantity.split("--");
		// Do we have different sizes/availabilities?
		if (bits.length>1) {
			// if so, then get quantity for the given size
			var otherBits = getInfoFromMODx(docID, ["stockItem_size"], 1).split("--");
			for (var i=0; i<bits.length; i++) {
				if (otherBits[i]==requiredSize) { 
					availableQuantity = bits[i];
				}
			}
		}
		return parseInt(availableQuantity, 10);
	}
	
	function validItemQuantity(docID, quantity, requiredSize) {
		quantity = parseInt(quantity, 10); // try to make it an integer
		if (!isNaN(quantity) && quantity>0 && quantity!=null) {
			var availableQuantity = getInfoFromMODx(docID, "stockItem_quantityRemaining", 1);
			availableQuantity = CheckForSizingQuantities(availableQuantity, docID, requiredSize);
			if (isNaN(availableQuantity) || availableQuantity==null) { // if error then play safe and set to 1, the most common value
				availableQuantity=1;
			}
			if (quantity>availableQuantity) {
				alert("WARNING: Only "+availableQuantity+" item(s) available.\n- I'm putting them in your basket.");
				quantity = availableQuantity;  // we've recovered as well as possible
			}
			return quantity;
		} else if (quantity==0) { 
			return 0;  // it's always fine to ask for zero of something
		} else {
			alert("WARNING: Quantities must be numbers (integers actually); nothing else.  I'm setting the quantity to one.");
			return 1;
		}
		return 0; // how can it get here?  send zero.
	}
		
	function promotionsCodeLookup_OLD(code) {
		// Look up code in DB
		promotionName  = "";
		promotionType  = "";
		promotionValue = "";
		var fieldValues = connTiedDBSelect(
			"CART_promotions", 
			"promo_code", 
			code, 
			"promo_name::promo_type::promo_value"
		);
		promotionName   = fieldValues[0];
		promotionType   = fieldValues[1];
		promotionValue  = fieldValues[2];
		return {"promotionName":promotionName, "promotionType":promotionType, "promotionValue":promotionValue};
	}
	
	function promotionsCodeLookup(code) {
		var promotionName = null;
		var promotionType = null;
		var promotionValue = null;
		if        (code=="PE_promo1") {
			promotionName = "Test promo code";
			promotionType = "SUB";
			promotionValue = "10";
		} 
                      if (code=="PLUM15") {
			promotionName = "Plum15";
			promotionType = "MULT";
			promotionValue = "0.15";
		}
//                      if (code=="SUMMER20") {
//			promotionName = "SUMMER20";
//			promotionType = "MULT";
//			promotionValue = "0.20";
//		}
//                      if (code=="APRILFOOL") {
//			promotionName = "April Fool";
//			promotionType = "MULT";
//			promotionValue = "0.15";
//		}
                       else if (code=="PE_friend") {
                       promotionName = "Friend promo code";
                       promotionType = "MULT";
                       promotionValue = "0.25";
                }
 	
		return {"promotionName":promotionName, "promotionType":promotionType, "promotionValue":promotionValue};
	}


	function valueOfPromotionsCode(subtotal) {
		var code = $('#promoField').val();
		if (code!="" && code!=null) {
			var promo = promotionsCodeLookup(code);
			promotionName  = promo.promotionName;
			promotionType  = promo.promotionType;
			promotionValue = promo.promotionValue;
			if (promotionName=="") {
				return 0.0;
			} else if (promotionName==null || promotionName==undefined) {
				alert("PROMOTION CODE NOT KNOWN: Please check code and re-enter.");
				return 0.0;
			} else {
				if (promotionType=="SUB") {
					return promotionValue;
				} else { 
					var retVal = subtotal*promotionValue;
					return retVal;
				}
			}
		}
		return 0.0;
	}
	
	// RE-CALCULATE THE VALUES FOR THE HTML TABLE
	function recalculate() {
		// ITEMS
		var status = true;
		$('tr').each(function() {
			if ($(this).find('input.quantityInput').size()>0) {
				var quantityTag  = $(this).find('input.quantityInput');
				var quantity     = parseInt(quantityTag.val(),10); // we must have an int
				var docID        = quantityTag.attr('title');
				var requiredSize = quantityTag.parent().prev().html();
				quantity         = validItemQuantity(docID, quantity, requiredSize); // gives us the best quantity we can get
				quantityTag.val(quantity);  // re-set to the the best quantity get could get from stock
				var price        = parseFloat( quantityTag.parent().next().attr('title') );  // we can have int or float
				var itemTotal    = quantity*price;
				$elem            = quantityTag.parent().next().next().next();
				$elem.attr('title',itemTotal);
				convertPrice($elem);
				if (quantity==0) { $(this).addClass('grey'); }
				else             { $(this).removeClass('grey'); }
			}
		});
		// SUBTOTAL
		var subtotal = 0.0;
		$('tr').each(function() {
			if ($(this).find('input.quantityInput').size()>0) {
				var rowTotal = parseFloat( $(this).find('td:last').attr('title') );
				subtotal += rowTotal;
			}
		});
		$('td#subtotal').attr( 'title', subtotal );
		convertPrice('td#subtotal');
		// SHIPPING
		subtotal += parseFloat( $('#shipping').attr('title') );
		// PROMOTION
		var promoValue = parseFloat(valueOfPromotionsCode(subtotal)); // needs subtotal if is a MULT promo
		$('#promotionReduction').attr('title',promoValue);
		convertPrice('#promotionReduction')
		if (promoValue>0) { 
			$('#promotionReduction').removeClass('dimmed').prev().removeClass('dimmed'); 
		} else { 
			$('#promotionReduction').addClass('dimmed').prev().addClass('dimmed'); 
		}
		subtotal -= parseFloat( $('#promotionReduction').attr('title') );  // deduct either the value of the promotion, or zero, if it's not a valid code
		// TAX
		var taxDecimal = parseFloat( $('input[name=taxDecimal]').val() );
		var tax = subtotal * taxDecimal;
		if (tax<0) { tax=0; }
		$('td#tax').attr("title",tax);
		convertPrice('td#tax');
		var taxIncluded = $('input[name=taxIncluded]').val();
		if (taxIncluded=="false" || taxIncluded==false) { // actually add the tax?
			subtotal += tax; 
			$('td#tax').removeClass('dimmed').prev().removeClass('dimmed');
		} else {
			$('td#tax').addClass('dimmed').prev().addClass('dimmed');		
		}
		// TOTAL
		if (subtotal<0 || isNaN(subtotal) || subtotal==undefined) { subtotal=0.0; }
		var totalCost = subtotal.toFixed(2);
		$('td#totalCost').attr('title',totalCost);
		convertPrice('td#totalCost');
		
		// convert all prices (done in allPages.js)

		return status;  // all ok?
	}		
	
	function setShippingCost() {
		var shippingCost = $('#shipppingChoice option:selected').val();
		$('#shipping').html("&pound;"+shippingCost);
		$('#shipping').attr('title',shippingCost);
		convertPrice('#shipping');
	}
	
	function updatePageValues() {
		// Validate and recalculate all fields (any errors will be alert the user directly by the specific validation-checker)
		if ( recalculate() ) {
			// Convert the HTML table to a cart string and store in the cart cookie
			var onscreenCart = "";
			var numItemsSuccessfullyAdded=0;
			$('tr input.quantityInput').each(function(i) {
				var quantity = $(this).val();
				var itemName = $(this).parent().prev().prev().html();
				var requiredSize = $(this).parent().prev().html();
				var nameBits = itemName.split(" - ");
				var ids      = nameBits[0];
				var idBits   = ids.split("/");
				var docID    = idBits[0];
				var stockItemID = idBits[1];
				var connector = "";
				if (numItemsSuccessfullyAdded!=0) { connector="****"; }
				if (quantity>0) {
					var cartItem = connector+docID+"||"+quantity+"||"+stockItemID+"||"+requiredSize;
					onscreenCart+=cartItem;
				}
				numItemsSuccessfullyAdded+=1;
			});
			var d = new Date();
			$.cookie("PE_cart", onscreenCart, 315705600, '/eco-ethical-fashion/');

			// Count the number of items in the cart and store their values
			var numItems = 0;
			$('tr input.quantityInput').each(function() {
				numItems+= parseInt($(this).val(),10);
			});
			var cartTotal = $('#totalCost').attr('title');
			if ( cartTotal==undefined || isNaN(cartTotal) ) { cartTotal=0.0; }
			if ( numItems==undefined  || isNaN(numItems) )  { numItems=0; }
			$.cookie("PE_cart_totals", numItems+"--"+cartTotal, d.getTime()+500000, '/eco-ethical-fashion/');

			// Get ready to send form to cart2
			var staticTableCopy = $('table').html();
			$('input[name=staticTableCopy]').val(staticTableCopy);
			$('input[name=grandTotal]').val( $('td#totalCost').attr('title') );
			$('input[name=grandTotalCurr]').val( $('td#totalCost').html() );
		}

	}
	

	function prepareForPayPal() {
		// Plum Ethical's own pass-through "||"-separated data
		var customString = "PE_INFO";

		// Set currency and country so prices and payment options are appropriate for locale
		var requiredCurrency = "GBP"; // default
		var country_code     = "GB"   // default
		var cDetails = $.cookie("PE_currency_Details").split("=");
		requiredCurrency = cDetails[0];
		if      (requiredCurrency=="GBP") { country_code="GB"; }
		else if (requiredCurrency=="USD") { country_code="US"; }
		else if (requiredCurrency=="EUR") { country_code="IE"; }
		else if (requiredCurrency=="JPY") { country_code="JP"; }
		else if (requiredCurrency=="SGD") { country_code="SG"; }
		else if (requiredCurrency=="CAD") { country_code="CA"; }
		else if (requiredCurrency=="NZD") { country_code="NZ"; }
		// get the cached conversion rate, or default to GBP if it's not set
		var conversionRate = 1.00;  // default rate
		if (requiredCurrency!="GBP") {
			var cookieName = "PE_GBP2"+requiredCurrency;
			var cr = $.cookie(cookieName);
			conversionRate = parseFloat( cr );
			if ( isNaN(conversionRate) || conversionRate==null || conversionRate==undefined ) { 
				conversionRate=1.00; // on error, default to GBP
			}
			else { 
				// Tell PayPal we're dealing in another currency
				$('input[name=currency_code]').val(requiredCurrency);
				$('input[name=country]').val(country_code);
			}			
		}
		// Fill-in Cart item Input fields for PayPal here on-the-fly
		// -- allows for both sized and non-sized items
		$('#paypalItemInputs').html(""); // ensure it starts empty
		$('tr.cartItem').each(function(i) {
			var ctr=i+1;
			var itemName     = $(this).children('td:eq(0)').html();
			var itemSize     = $(this).children('td:eq(1)').html();
			var itemQuantity = $(this).children('td:eq(2)').find('input').val();
			var itemCost     = Math.round(100* parseFloat( $(this).children('td:eq(3)').attr('title') ) * conversionRate)/100;
			$('#paypalItemInputs').append( $("<input type='hidden' name='item_name_"+ctr+"' value='"+itemName+"' />") );
			$('#paypalItemInputs').append( $("<input type='hidden' name='amount_"+ctr+"'    value='"+itemCost+"' />") );
			$('#paypalItemInputs').append( $("<input type='hidden' name='quantity_"+ctr+"'  value='"+itemQuantity+"' />") );
			if (itemSize!="") { 
				$('#paypalItemInputs').append( $("<input type='hidden' name='on0_"+ctr+"'    value='Size' />") );
				$('#paypalItemInputs').append( $("<input type='hidden' name='os0_"+ctr+"'    value='"+itemSize+"' />") );
			}
		});
		// Shiping
		var shippingCost = Math.round(100* parseFloat( $('#shipppingChoice option:selected').val() ) * conversionRate)/100;
		if (isNaN(shippingCost)) { shippingCost=0.00; } // play safe
		$('#paypalItemInputs').append( $("<input type='hidden' name='handling_cart'    value='"+shippingCost+"' />") );
		// Discounts		
		var code = $('#promoField').val();
		var fixedDiscount  = 0.00;
		var rateDiscount   = 0.00;
		if (code!="" && code!=null) {
			var promo = promotionsCodeLookup(code);
			var promotionType  = promo.promotionType;
			var promotionValue = promo.promotionValue;
			if (promotionType=="SUB") { fixedDiscount = promotionValue * conversionRate; } 
			else                      { rateDiscount  = parseInt(100* promotionValue, 10); } //between 0 and 100
			promotionName  = promo.promotionName;
			customString    += "||"+promotionName;
		}		
		if (fixedDiscount>0) {
			$('#paypalItemInputs').append( $("<input type='hidden' name='discount_amount_cart'    value='"+fixedDiscount+"' />") );
		} 
		if (rateDiscount>0) {
			$('#paypalItemInputs').append( $("<input type='hidden' name='discount_rate_cart'    value='"+rateDiscount+"' />") );
		}
		// Plum Ethical's own pass-through "||"-separated data
		$('input[name=custom]').val(customString);	
//alert( $('#paypalItemInputs').html() );
	}	

	
	$(document).ready(function() {
		// Pressing return on an (altered) quantity field
		$("input.quantityInput").keypress(function (e) {
			if (e.which == 13) {
				var searchValue = $(this).val();   /// ???
				updatePageValues();
				return false;  // kill any browser-native actions normally caused by the return key
			}
		});
		
		// Setting the Shipping value
		$('#shipppingChoice').change(function() {  
			setShippingCost(); 
			updatePageValues(); 
		});
		setShippingCost();
		// Setting the Promotions code
		$('#promoField').keypress(function (e) {  if (e.which==13) {updatePageValues();} });
		// Clicking the Continue button
		$('#continueButton').click(function() { history.go(-1); return false; });
		// Clicking the Recalculate button
		$('#recalculateButton').click(function() {  updatePageValues();  });
		// Clicking the Checkout button
		$('#checkoutButton').click(function() {
			$("#spinnerBG").show();
			updatePageValues();  // needed to apply the promo code if the user has returned via back button
			prepareForPayPal();
			$('#cart1').attr('action','https://www.paypal.com/cgi-bin/webscr');
			$('#cart1').attr('method','post');
			$('input[name=chosenShippingMethod]').val( $('#shipppingChoice option:selected').val() );
			$('#cart1').submit();
			//alert("ON THE NEXT PAGE: You can use your Credit Card by clicking the 'Continue' link, next to the credit card symbols.");
		});
		
		// Initial values
		// - promotions are re-set every time the page is refreshed (FFox might retain the field, but it still needs to be re-entered)
		var promoValue     = 0.00;
//		$('#promoField').val("");  // reset the promo field
		$('#promotionReduction').html("-&pound;"+promoValue.toFixed(2));
		$('#promotionReduction').attr('title',0.00);		
		// - the initial pages values
		updatePageValues();
	});

