//----------------------------------------------------------------
// Definition of new Product Object 
// 'new' will create a new instace of object and set parameter data into object
function Product(code, name, price, items, dest, qty, limit) {
	this.code 	= code;		// product code - written to cookie, used to recreate shopping basket from cookie
	this.name 	= name;		// product name - displayed on order
	this.price 	= price;	// product price
	this.items 	= items;	// Number of items in product - used for shipping calculations.  Only 4 items/shipment
	this.dest 	= dest;		// Permitted shipping destinations - ALL or list of permitted destinations
	this.qty 	= qty;		// number of products selected
	this.limit 	= limit;	// limit on number of items for this product (Lemon Myrtle is 2, others 4)
	return this;
}

//----------------------------------------------------------------
// Definition of new Shipping Object 
// 'new' will create a new instace of object and set parameter data into object
function ShippingPrice(name, prices) {
	this.name 	= name;
	this.pricePerItem = String(prices).split(",");

	return this;
}
//----------------------------------------------------------------
// Global variables
var myCart 					= new Array();
var myCatalog 			= new Array();
var myShipping			= new Array();
var numShipItems		= 0;
var totalProductPrice 	= 0.00;
var totalShipping 		= 0.00;
var shippingDestination = getDestination();

function setDestination(index) {
	shippingDestination = index;
	writeCookie("ship", shippingDestination, 24);	
}

function getDestination() {
	var dest = readCookie("ship");
	if (dest == "" || dest == null || dest == "undefined") {
		dest = 0;
	}
	return dest;
}

function addToShippingPrices(dest, prices) {
	myShipping[ myShipping.length ] = new ShippingPrice(dest, prices);
}

function addToCatalog(code, name, price, items, dest, qty, limit) {
	myCatalog[ myCatalog.length ] = new Product(code, name, price, items, dest, qty, limit);
}

function findProductInCatalog(code) {
	for (var i = 0; i < myCatalog.length; i++) {
		if (myCatalog[ i ].code == code) {
			return myCatalog[ i ];
		}
	}
	return -1;
}

function findItemInCart(code) {
	for (var i = 0; i < myCart.length; i++) {
		if (myCart[ i ].code == code) {
			return i;
		}
	}
	return -1;
}

function createCartFromCookie() {
	var prodParams;
	var thisProd;
	var cart = readCookie("cart");
	
	// Individual products are separated by the | character
	if (cart != "")cart = cart.split("|");
	
	for (var i = 0; i < cart.length; i++) {
		// Product info separated by "," - code,qty 
		prodParams 		= cart[i].split(",");
		thisProd 		= findProductInCatalog(prodParams[0]);
		myCart[ i ] 	= thisProd;
		myCart[ i ].qty = prodParams[1];
	}
}

function saveCartToCookie() {
	var cart = "";

	for (var i = 0; i < myCart.length; i++) {
		// Add product delimeter "|"
		cart += (cart.length > 0 )? "|" : "";
		// Add product code,qty
		cart += myCart[ i ].code + "," + myCart[ i ].qty;
	}	
	writeCookie("cart", cart, 24);	
}

function addToCart(form, code, selectQty) {
	// Retrieve Product Code from selection box
	var obj = eval("form."+code);
	
	// Get reference to product object from catalog
	var thisProd = findProductInCatalog(obj.options[obj.selectedIndex].value);
	var cartNo = findItemInCart(obj.options[obj.selectedIndex].value);

	// Retrieve Qty from selection box
	obj = eval("form."+selectQty);

	// if Product in Catalog but not already in Cart - Add to Cart
	if (thisProd && cartNo < 0) {
		var num = myCart.length;
		myCart[ num ] = thisProd;
		myCart[ num ].qty = obj.options[obj.selectedIndex].text;
	} else if (thisProd && cartNo >= 0) {
		myCart[cartNo].qty = obj.options[obj.selectedIndex].text;
	}	
	saveCartToCookie();
}

function deleteItemFromCart(itemNo) {
	// Delete item from Cart array
	for (var i = itemNo; i < myCart.length-1; i++)
	{
		myCart[i] = myCart[i+1];
	}
	myCart.length -= 1;
}

function updateItemInCart(itemNo, form, selectQty) {
	// Retrieve Qty from selection box
	var obj = eval("form."+selectQty);
	var qty = parseFloat(obj.options[obj.selectedIndex].text);

	if (qty > 0 ) {
		myCart[ itemNo ].qty = qty;
	} else {
		deleteItemFromCart(itemNo);
	}
	saveCartToCookie();	
}

function clearOrder() {
	writeCookie("cart", "", 24);	
}

function refreshPage() {
	// Remove any anchor tags from URL so page will always re-display from the top
	var strURL = window.location.href;
	var pgAnchor = strURL.indexOf("#");
	if (pgAnchor >=0)strURL = strURL.substr(0, pgAnchor);
	window.location.href = strURL;	
}
//----------------------------------------------------------
//-- calculate the extra postage costs for 1kg packs
// -- only use the 1kg packs if the product codes are found in the shopping cart
//----------------------------------------------------------



//----------------------------------------------------------------
// Calculate order prices
//
function calculateProductAndShippingCosts() {
// Re-set value
	totalProductPrice = 0;
	totalShipping = 0;
	numShipItems = 0;	
	for (var i = 0; i < myCart.length; i++) {
		totalProductPrice += parseFloat(myCart[ i ].price * myCart[ i ].qty);
		numShipItems += Math.ceil(parseFloat(myCart[ i ].qty * myCart[ i ].items));
	}	
	if ( numShipItems > 0 && numShipItems < 5) {
		totalShipping =  parseFloat(myShipping[shippingDestination].pricePerItem[numShipItems-1]);
	} else {
		totalShipping = "NA";			
	}
	

}




//----------------------------------------------------------------
// Generate HTML code for Basket and Order pages
//
function getCartProductPriceHTML() {
	var strHMTL = "";
	
	strHMTL += '<input name="oPrice" type="hidden" id="oPrice" value="'+ totalProductPrice +'" />';
	strHMTL += "$" + totalProductPrice.toFixed(2);
	
	return strHMTL;
}

function getCheckoutBtnOrErrMsgHTML() {
	var strMsg = "";
	var strHTML = "";
	
	if (numShipItems >= 5) {
		strMsg += "You have 5 or more items in your basket.  Please place separate orders or contact us for shipping costs.";
	} else if (numShipItems == 0) {
		strMsg += "Please add one of our wonderful products to your shopping basket.";	
	}
	
	// Check if any products in basket can't be shipped to selected destination
	for (var i=0; i < myCart.length; i++) {
		// Product delivery is restricted and selected shipping destination zone is not in allowed list
		if (myCart[i].dest != "ALL" && String(myCart[i].dest).indexOf(myShipping[shippingDestination].name) < 0) {			
			strMsg += "Some Products in your basket can not be shipped to your selected destination";
			break;
		}
	}
	
	if (strMsg != "") {
		strHTML = '<tr><td colspan="54" align="right" bgcolor="#EAE4C6" class="borderBBrown"><span class="textRed">'+strMsg+'</span></td></tr>';
	} else {
		strHTML = '<tr><td colspan="5" align="right" bgcolor="#BBA46F">';
		strHTML += '<input type="submit" name="Submit" value="Proceed to Checkout" /></td></tr>';
	}
	
	return strHTML;
}

function getCartShippingPriceHTML() {
	var strHTML = "";
	
	if (isNaN(totalShipping)) {
		strHTML += '<input name="oShipping" type="hidden" id="oShipping" value="0.00" />$0.00';	
	} else {
		strHTML += '<input name="oShipping" type="hidden" id="oShipping" value="'+ totalShipping +'" />$';
		strHTML += parseFloat(totalShipping).toFixed(2);	
	}
	
	return strHTML;
}

function getCartTotalPriceHTML() {
	var strHTML = "";
	
	if (isNaN(totalShipping)) {
		strHTML += '<input name="oTotal" type="hidden" id="oTotal" value="0.00" />$0.00';
	} else {
		strHTML += '<input name="oTotal" type="hidden" id="oTotal" value="'+ parseFloat(totalShipping+totalProductPrice).toFixed(2) +'" />$';
		strHTML += parseFloat(totalShipping+totalProductPrice).toFixed(2);	
	}	
	
	return strHTML;
}

function getCartBasketPageHTML() {
	var strHTML = "";
	
	if (myCart.length > 0) {
		for (var i = 0; i < myCart.length; i++) {
			strHTML += "<tr>";
			strHTML += '<td bgcolor="#EAE4C6" class="borderBRBrown" align="right" nowrap>';
			strHTML += "<select name=qty" + i + ">";
			
			var j = 0;
			while ( Math.ceil(myCart[i].items * j) <= myCart[i].limit) {
				if (myCart[i].qty == j) {
					strHTML += '<option selected>'+j +'</option>';
				} else {
					strHTML += "<option>"+j+"</option>";
				}
				j++;
			}
			strHTML += "</select>";
			strHTML += '<input type="button" name="change" value="Change" onclick="javascript:updateItemInCart('+i+',this.form,\'qty'+i+'\');refreshPage();"/>';
			strHTML += '</td>';
			strHTML += '<td bgcolor="#EAE4C6" class="borderBRBrown">'+myCart[i].name+'<input name="name'+i+'" type="hidden" id="name'+i+'" value="'+myCart[i].name+'" /></td>'
			strHTML += '<td bgcolor="#EAE4C6" class="borderBRBrown" align="center">'+Math.ceil(parseFloat(myCart[i].items * myCart[i].qty))+'<input name="items'+i+'" type="hidden" id="items'+i+'" value="'+Math.ceil(parseFloat(myCart[i].items * myCart[i].qty))+'" /></td>'
			strHTML += '<td bgcolor="#EAE4C6" class="borderBRBrown" align="right">$'+parseFloat(myCart[i].price).toFixed(2)+'<input name="price'+i+'" type="hidden" id="price'+i+'" value="'+myCart[i].price+'" /></td>'
			strHTML += '<td bgcolor="#EAE4C6" class="borderBBrown" align="right">$'+parseFloat(myCart[i].price * myCart[i].qty).toFixed(2)+'<input name="ptotal'+i+'" type="hidden" id="ptotal'+i+'" value="'+parseFloat(myCart[i].price * myCart[i].qty).toFixed(2)+'" /></td>'
			strHTML += "</tr>";
		}
		strHTML += '<input name="numProducts" type="hidden" id="numProducts" value="'+myCart.length+'" />'
		strHTML += '    <tr>';
        strHTML += '     <td align="right" bgcolor="#EAE4C6" class="borderBRBrown"><input type="button" name="Button" value="Clear Order" onclick="clearOrder();refreshPage();"/></td>';
        strHTML += '      <td bgcolor="#EAE4C6" class="borderBRBrown">&nbsp;</td>';
        strHTML += '      <td bgcolor="#EAE4C6" class="borderBRBrown">&nbsp;</td>';
        strHTML += '      <td bgcolor="#EAE4C6" class="borderBRBrown">&nbsp;</td>';
        strHTML += '      <td bgcolor="#EAE4C6" class="borderBBrown">&nbsp;</td>';
        strHTML += '    </tr>';
	} else {
		strHTML += '<tr><td colspan="5" class="borderBBrown">Your basket is empty</td></tr>'
	}
	return strHTML;
}

function getShippingDestListHTML() {
	var strHTML = ""
   
	strHTML += '<select name="shipDestination" id="shipDestination" onchange="setDestination(this.options[this.selectedIndex].value);refreshPage();">';
	for (var i=0; i < myShipping.length; i++) {
		if (shippingDestination == i) {
	 		strHTML += '<option selected="selected" value="'+i+'">'+myShipping[i].name+'</option>';
		} else {
	 		strHTML += '<option value="'+i+'">'+myShipping[i].name+'</option>';
		}
	}
	strHTML += '</select>';
	
	return strHTML;
}



//----------------------------------------------------------------
// Read/Write Cookie Functions
//
function chkCookiesEnabled() {
	var tmpcookie = new Date();
	chkcookie = (tmpcookie.getTime() + '');
	document.cookie = "chkcookie=" + chkcookie + "; path=/";
	var status = true
	if (document.cookie.indexOf(chkcookie,0) < 0) {
		status = false;
	}
	return status;
}
function readCookie(name) {
  var cookieValue = "";
  var txt = name + "=";
  if(document.cookie.length > 0) { 
    offset = document.cookie.indexOf(txt);
    if (offset != -1) { 
      offset += txt.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end));
    }
  }

  return cookieValue;
}
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours) {
  var expire = "";
  if(hours != null) {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
	path = "; path=/;"
  }
  document.cookie = name + "=" + escape(value) + expire + path;
}



//----------------------------------------------------------------
// Page Load Initialization Steps
//
// Create Product Catalog

addToCatalog("1KGRAINBERRIES","1kg pack of Rainberries Only",32,1,"ALL",0,4);
addToCatalog("1KGRAINCHERRIES","1kg pack of Raincherries Only",32,1,"ALL",0,4);
addToCatalog("1KGSALSA","1kg pack of Rainforest Salsa Only",32,1,"ALL",0,4);
addToCatalog("1KGCHUTNEY","1kg pack of Rainforest Chutney Only",32,1,"ALL",0,4);
addToCatalog("1KG-1-EACH","1 of each 1kg pack. Rainberry, Raincherry, Salsa, Chutney",120,4,"ALL",0,4);
addToCatalog("1KGCUSTOM4","Custom order - any 4 1kg packs",120,4,"ALL",0,4);



addToCatalog("RFGIFT1","Rainforest Fruit - 1 Gift Box",15,1,"ALL",0,4);
addToCatalog("RFGIFT2","Rainforest Fruit - 2 Gift Boxes",28,2,"ALL",0,4);
addToCatalog("150G4PACK","4 x 150g Rainforest Fruit Packs, Rainberry, Raincherry, Chutney, Salsa - 1 of each",30,4,"ALL",0,4);
addToCatalog("150G4SALSAPACK","4 x 150g Rainforest Salsa Packs",30,4,"ALL",0,4);
addToCatalog("150G4CHUTPACK","4 x 150g Rainforest Chutney Packs",30,4,"ALL",0,4);
addToCatalog("150G4BERRYPACK","4 x 150g Rainforest Fruit Packs, Rainberry only",30,4,"ALL",0,4);
addToCatalog("150G4CHERRYPACK","4 x 150g Rainforest Fruit Packs, Raincherry only",30,4,"ALL",0,4);
addToCatalog("150G2BER2CHERPACK","4 x 150g Rainforest Fruit Packs, Rainberry(2), Raincherry(2)",30,4,"ALL",0,4);
addToCatalog("150G2CHUT2SALSAPACK","4 x 150g Rainforest Chutney(2), Rainforest Salsa(2) packs",30,4,"ALL",0,4);
addToCatalog("150GCUSTOM4PACK","4 x 150g Rainforest Fruit Packs (Custom Order)",30,4,"ALL",0,4);






//addToCatalog("1KGPOUCH4SALSAPACK","4 x 1KG Rainforest Salsa Pack",120,4,"ALL",0,4);
//addToCatalog("1KGPOUCH4CHUTPACK","4 x 1KG Rainforest Chutney Pack",120,4,"ALL",0,4);
//addToCatalog("1KGPOUCH4BERRYPACK","4 x 1KG Rainforest Fruit Pack, Rainberry",120,4,"ALL",0,4);
//addToCatalog("1KGPOUCH4CHERRYPACK","4 x 1KG Rainforest Fruit Pack, Raincherry",120,4,"ALL",0,4);
//addToCatalog("1KGPOUCH2BER2CHERPACK","4 x 1KG Rainforest Fruit Pack, Rainberry(2), Raincherry(2)",120,4,"ALL",0,4);
//addToCatalog("1KGPOUCH2CHUT2SALSAPACK","4 x 1KG Rainforest chutney(2), rainforest salsa(2)",120,4,"ALL",0,4);

addToCatalog("LMGROUND","50g sachet of Dried Ground Lemon Myrtle Leaf [AU only]",10,.2,"Australia",0,2);
addToCatalog("LMWHOLE","50g sachet of Dried Whole Lemon Myrtle Leaf [AU only]",10,.2,"Australia",0,2);
addToCatalog("MACYUMS1","1 Box of Macadami-Yums&#8482; [AU only]",15,1,"Australia",0,4);
addToCatalog("CRUMBLE1","1 400g Rainforest Crumble Cake [AU only]",15,1,"Australia",0,4);
addToCatalog("APPLE1","1 450g Rainberry Apple Cake w Butterscotch Icing [AU only]",15,1,"Australia",0,4);
addToCatalog("MACYUMS2","2 Boxes of Macadami-Yums&#8482; [AU only]",28,2,"Australia",0,4);
addToCatalog("CRUMBLE2","2 400g Rainforest Crumble Cakes [AU only]",28,2,"Australia",0,4);
addToCatalog("APPLE2","2 450g Rainberry Apple Cakes w Butterscotch Icing [AU only]",28,2,"Australia",0,4);
addToCatalog("BAKECOMBO","3 (1 each of: Macadami-Yums&#8482;, Rainforest Crumble, Rainberry Apple) [AU only]",42,3,"Australia",0,4);
addToCatalog("HAMPER","Galeru Sampler Gift Hamper (All 3 baked products + rainforest fruits box) [AU only]",55,4,"Australia",0,4);

// Create Shipping Destination Costs


function getONEkgshipping() {
	var j = 0;
	
			for (var i = 0; i < myCart.length; i++) {
				if ((myCart[i].code == '1KGRAINBERRIES') || (myCart[i].code == '1KGRAINCHERRIES') || (myCart[i].code == '1KGSALSA') || (myCart[i].code == '1KGCHUTNEY')){
					
					// calculate the postage rates for individual 1kg purchases – 1 pack only  
					addToShippingPrices("Australia","10,10,15,18");
					addToShippingPrices("New Zealand","25,37,45,53");
					addToShippingPrices("Asia/Pacific","33,59,73,88");
					addToShippingPrices("USA/etc","42,75,94,113");
					addToShippingPrices("Rest of World","42,75,94,113");
				} 
				// calculate the postage rates for individual 4x 1kg purchases – 4 packs
				else if ((myCart[i].code == '1KG-1-EACH') || (myCart[i].code == '1KGCUSTOM4')){
					addToShippingPrices("Australia","18,22,31,35");
					addToShippingPrices("New Zealand","53,84,114,146");
					addToShippingPrices("Asia/Pacific","88,146,204,262");
					addToShippingPrices("USA/etc","113,190,268,345");
					addToShippingPrices("Rest of World","113,190,268,345");
				}
				// calculate the postage rates for individual 4 pack 150g purchases – 4 packs
				else {
					addToShippingPrices("Australia","9,10,11,14");
					addToShippingPrices("New Zealand","12,22,32,32");
					addToShippingPrices("Asia/Pacific","14.50,26.50,38.50,38.50");
					addToShippingPrices("USA/etc","18,34,44,54");
					addToShippingPrices("Rest of World","20,38,50,60");
				}
				//j++;
			}
			
			//addToShippingPrices("Australia","9,10,11,12");			
}



// Read Saved Cart Items from Cookie
createCartFromCookie();

getONEkgshipping();
// Calculate Product and Shipping Costs
calculateProductAndShippingCosts();


