//----------------------------------------------------------------
// Definition of new Product Object 
// 'new' will create a new instace of object and set parameter data into object
function Product(code, name, price, weight, 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.weight = weight;	// 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 shipCountryID 			= 12;
var shipCountry 			= "AU";
var shipPostcode 			= "";
var shipWeight 				= 0;

function setDestination(id, cntry, pcode) {	
	var ship = cntry + "," + pcode+ "," + id;
	writeCookie("dest", ship, 24);	
	shipCountryID = id;
	shipCountry = cntry;
	shipPostcode = pcode;
}

function getDestination() {
	var dest = readCookie("dest")
	if (dest != "") {
		dest = dest.split(",");
		shipCountry = dest[0];
		shipPostcode = dest[1];
		shipCountryID = dest[2];
	}
	return dest;
}

function getPostage() {
	// get estimated postage
	var post = readCookie("post")
	if (post != "") {
		totalShipping	= post;
	}
}

function setPostage(cost) {
	// estimated postage from DRC
	totalShipping	= parseFloat(cost);
	writeCookie("post", totalShipping, 24);	
}

function getNumCartItems() {
	return myCart.length;
}

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 addItemToCart(form, code, c, q) {
	// If code not supplied, retrieve Product Code from selection box
	if (code == "") {
		code = ( (eval("form."+c) != null) ? eval("form."+c+".options[form."+c+".selectedIndex].value"):"" );
	}
	
	// Get reference to product object from catalog
	var thisProd = findProductInCatalog(code);
	var cartNo = findItemInCart(code);

	// Retrieve Qty from selection box
	obj = eval("form."+q);

	// 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.value;
	} else if (thisProd && cartNo >= 0) {
		myCart[cartNo].qty = obj.value;
	}	
	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.value);
	if (qty > 0 ) {
		myCart[ itemNo ].qty = qty;
	} else {
		deleteItemFromCart(itemNo);
	}
	saveCartToCookie();	
	calculateOrderPriceWeight();
	form.w.value = shipWeight;
	form.action = "view_cart.asp";
	form.submit();
}

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 order prices
//
function calculateOrderPriceWeight() {
// Re-set value
	totalProductPrice = 0;
	shipWeight = 0;
	for (var i = 0; i < myCart.length; i++) {
		totalProductPrice += parseFloat(myCart[ i ].price * myCart[ i ].qty);
		shipWeight += parseFloat(myCart[ i ].weight * myCart[ i ].qty); 
	}	
}


//----------------------------------------------------------------
// Generate HTML code for View Cart button, Basket and Order pages
//
function btnViewCartHTML() {
	var strHTML = "";

	strHTML += 'Cart has: '+myCart.length+' items';
	strHTML += '<input name="w" type="hidden" id="w" value="'+shipWeight+'"/>';	
	strHTML += '<input name="c" type="hidden" id="c" value="'+shipCountry+'"/>';	
	strHTML += '<input name="p" type="hidden" id="p" value="'+shipPostcode+'"/>';	
	
	return strHTML;
}

function getCartProductPriceWeightHTML() {
	var strHTML = "";
	
	strHTML += '<input name="w" type="hidden" id="w" value="'+shipWeight+'"/>';	
	strHTML += '<input name="prodTotal" type="hidden" id="prodTotal" value="'+ totalProductPrice.toFixed(2) +'" />';
	strHTML += "$" + totalProductPrice.toFixed(2);
	
	return strHTML;
}

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="shipTotal" type="hidden" id="shipTotal" value="0.00" />$0.00';	
	} else if (shipWeight >= 20000) {
		strHTML += '<input name="shipTotal" type="hidden" id="shipTotal" value="0.00" />NA';	
	} else {
		strHTML += '<input name="shipTotal" type="hidden" id="shipTotal" value="'+ totalShipping +'" />$';
		strHTML += parseFloat(totalShipping).toFixed(2);	
	}
	
	return strHTML;
}

function getCartTotalPriceHTML() {
	var strHTML = "";
	
	if (isNaN(totalShipping)) {
		strHTML += '<input name="orderTotal" type="hidden" id="orderTotal" value="0.00" />$0.00';
	} else if (shipWeight >= 20000) {
		strHTML += '<input name="orderTotal" type="hidden" id="orderTotal" value="0.00" />NA';	
	} else {
		var total = parseFloat(totalShipping) + parseFloat(totalProductPrice);
		strHTML += '<input name="orderTotal" type="hidden" id="orderTotal" value="'+ parseFloat(total).toFixed(2) +'" />$';
		strHTML += 	parseFloat(total).toFixed(2);	
	}	
	
	return strHTML;
}

function getCartPageHTML() {
	var strHTML = "";
	
	if (myCart.length > 0) {
		for (var i = 0; i < myCart.length; i++) {
			strHTML += "<tr>";
			strHTML += '<td bgcolor="#CCFF99" align="right" nowrap>';
			strHTML += '<input name="q'+i+'" type="text" id="q'+i+'" class="cartInputNumText" size="3" value="'+myCart[i].qty+'">';
			strHTML += "<input type=\"button\" name=\"change\" value=\"Change\" onclick=\"javascript:updateItemInCart("+i+",this.form,'q"+i+"');\"/>";
			strHTML += '</td>';
			strHTML += '<td bgcolor="#CCFF99" >'+myCart[i].name+'<input name="name'+i+'" type="hidden" id="name'+i+'" value="'+myCart[i].name+'" />';			
			strHTML += '<input name="code'+i+'" type="hidden" id="code'+i+'" value="'+myCart[i].code+'" /></td>'
			strHTML += '<td bgcolor="#CCFF99" align="center">'+(myCart[i].weight*myCart[i].qty)+'<input name="weight'+i+'" type="hidden" id="weight'+i+'" value="'+(myCart[i].weight*myCart[i].qty)+'" /></td>'
			strHTML += '<td bgcolor="#CCFF99"  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="#CCFF99" 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="#CCFF99" ><input type="button" name="Button" value="Clear Order" onclick="clearOrder();refreshPage();"/></td>';
        strHTML += '      <td bgcolor="#CCFF99" >&nbsp;</td>';
        strHTML += '      <td bgcolor="#CCFF99" >&nbsp;</td>';
        strHTML += '      <td bgcolor="#CCFF99" >&nbsp;</td>';
        strHTML += '      <td bgcolor="#CCFF99" >&nbsp;</td>';
        strHTML += '    </tr>';
	} else {
		strHTML += '<tr><td colspan="5">Your basket is empty</td></tr>'
	}
	return strHTML;
}

function getOrderPageHTML() {
	var strHTML = "";
	
	if (myCart.length > 0) {
		for (var i = 0; i < myCart.length; i++) {
			strHTML += "<tr>";
			strHTML += '<td bgcolor="#FFFFFF" >'+myCart[i].name+'<input name="name'+i+'" type="hidden" id="name'+i+'" value="'+myCart[i].name+'" />';			
			strHTML += '<input name="code'+i+'" type="hidden" id="code'+i+'" value="'+myCart[i].code+'" /></td>'
			strHTML += '<td bgcolor="#FFFFFF" align="center">'+myCart[i].qty+'<input name="q'+i+'" type="hidden" id="q'+i+'" value="'+myCart[i].qty+'" /></td>'
			strHTML += '<td bgcolor="#FFFFFF" align="right">'+(myCart[i].weight*myCart[i].qty)+'<input name="weight'+i+'" type="hidden" id="weight'+i+'" value="'+(myCart[i].weight*myCart[i].qty)+'" /></td>'
			strHTML += '<td bgcolor="#FFFFFF" 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="#FFFFFF" 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+'" />'
	}
	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(code, name, price, items, dest, qty, limit) {


// 3 pack of 200g jars
addToCatalog("200DLJ","Desert Lime Jam (200g) - 3 pack",24,1310,"ALL",0,4);
addToCatalog("200DLOM","Desert Lime &amp; Orange Marmalade (200g) - 3 pack",24,1310,"ALL",0,4);
addToCatalog("200DLTJ","Desert Lime &amp; Tomato Jam (200g) - 3 pack",24,1310,"ALL",0,4);
addToCatalog("200SMPL","Jam Delights - 1 of each flavour",24,1310,"ALL",0,4);

// 24 in carton of 200g jars
addToCatalog("200DLJCRTN","Desert Lime Jam (200g) - 24 in carton",144,9800,"ALL",0,4);
addToCatalog("200DLOMCRTN","Desert Lime &amp; Orange Marmalade (200g) - 24 in carton",4,9800,"ALL",0,4);
addToCatalog("200DLTJCRTN","Desert Lime &amp; Tomato Jam (200g) - 24 in carton",4,9800,"ALL",0,4);
addToCatalog("200SMPLCRTN","Jam Delights - 4 of each flavour",4,9800,"ALL",0,4);

// 3 pack of 250g jars
addToCatalog("250DLG","Desert Limes in Syrup (250 g) - 3 pack",27,1620,"ALL",0,4);
addToCatalog("250ADLS","Apple &amp; Desert Lime Sauce (250 g) - 3 pack",27,1620,"ALL",0,4);
addToCatalog("250DLC","Desert Lime Chutney (250 g) - 3 pack",27,1620,"ALL",0,4);
addToCatalog("250SMPL","Gourmet Sampler - 1 of each flavour",27,1620,"ALL",0,4);
// 24 in carton of 250g jars
addToCatalog("250DLGCRTN","Desert Limes in Syrup (250 g) - 24 in carton",168,12250,"ALL",0,4);
addToCatalog("250ADLSCRTN","Apple &amp; Desert Lime Sauce (250 g) - 24 in carton",168,12250,"ALL",0,4);
addToCatalog("250DLCCRTN","Desert Lime Chutney (250 g) - 24 in carton",168,12250,"ALL",0,4);
addToCatalog("250SMPLCRTN","Gourmet Sampler - 8 of each flavour",168,12250,"ALL",0,4);

// 100g Tubs
addToCatalog("100SMPL","Variety Box - all six flavours",22.50,630,"ALL",0,4);
addToCatalog("100PASTE","Desert Lime Paste - six 100g tubs",22.50,630,"ALL",0,4);
addToCatalog("100DLTJ","Desert Lime &amp; Tomato Jam - six 100g tubs",22.50,630,"ALL",0,4);
addToCatalog("100DLJ","Desert Lime Jam - six 100g tubs",22.50,630,"ALL",0,4);
addToCatalog("100DLC","Desert Lime Chutney - six 100g tubs",22.50,630,"ALL",0,4);
addToCatalog("100ADLS","Apple &amp; Desert Lime Sauce - six 100g tubs",22.50,630,"ALL",0,4);
addToCatalog("100DLOM","Desert Lime &amp; Orange Marmalade - six 100g tubs",22.50,630,"ALL",0,4);

// Jam Delights
addToCatalog("200SMPL","Jam Delights - 1 of each flavour",24,1310,"ALL",0,4);
// Gourmet Gift Box
addToCatalog("250SMPL","Gourmet Gift Box - 1 of each flavour",27,1620,"ALL",0,4);
// Cordial
addToCatalog("CORDIAL","Desert Lime Cordial - 2 pack",14,2560,"ALL",0,4);
addToCatalog("CORDIALCRTN","Desert Lime Cordial - 12 in carton",90,13500,"ALL",0,4);

// 1kg Pail
addToCatalog("1KGPAILDLG","Desert Limes in Syrup 1kg pail",22.50,1200,"ALL",0,4);

// addToCatalog(code, name, price, weight, dest, qty, limit)
// Desert Lime Aioli and Curd packs and cartons
addToCatalog("300DLAIOLI","Desert Lime Aioli (300g) - pack of 3",27,1700,"ALL",0,4);
addToCatalog("300DLCURD","Desert Lime Curd (300g) - pack of 3",27,1700,"ALL",0,4);
addToCatalog("300DLAIOLICRTN","Desert Lime Aioli (300g) - 18 in carton",162,11000,"ALL",0,4);
addToCatalog("300DLCURDCRTN","Desert Lime Curd (300g) - 18 in carton",162,11000,"ALL",0,4);
addToCatalog("300ACSMPLCRTN","Gourmet Sampler - 9 of each flavour",162,11000,"ALL",0,4);


// Read Saved Cart Items from Cookie
createCartFromCookie();

// Calculate Product and Shipping Costs
calculateOrderPriceWeight();

// Read saved shipping info from cookie
getDestination();
getPostage();

