// JavaScript Document
//----------------------------------------------------------------
// Definition of new CartItem Object 
// 'new' will create a new instace of object and set parameter data into object
function CartItem(code, name, weight, price, size, fabric, qty, option1) {
	this.code 		= code;				// product code - written to cookie, used to recreate shopping basket from cookie
	this.name 		= name;				// product name - displayed on order
	this.weight 	= weight;			// product weight per unit - used to determine shipping costs
	this.price 		= price;			// product price
	this.size 		= size;				// size ordered 
	this.fabric 	= fabric;			// fabric ordered 
	this.qty 	  	= qty;				// number of products selected
	this.option1 	= option1;		// option1
	return this;
}
//----------------------------------------------------------------
// Definition of new Product Object 
// 'new' will create a new instace of object and set parameter data into object
function Product(code, name, weight) {
	this.code 	= code;				// product code - written to cookie, used to recreate shopping basket from cookie
	this.name 	= name;				// product name - displayed on order
	this.weight = weight;			// weight per unit
	return this;
}

//----------------------------------------------------------------
// Global variables
var myCart 		= new Array();		// Array to hold ordered products
var myCatalog = new Array();		// Array of products listed on site for sale
var totalProd = 0;							// Total product price set by calcCartPriceGST() function		
var totalGST 	= 0;							// Total GST for order set by calcCartPriceGST() function	
var totalPostage = 0;						// Total Postage costs set by calcCartPriceGST() function	
var totalWeight = 0;						// Total weight for order
var numItems 	= 0;							// Total items in order set by calcCartPriceGST() function	
var strErrorMsg = "";						// Error message for problems calculating postage
//----------------------------------------------------------------
// Cart Functions
function addToCatalog(code, name, type) {
	myCatalog[ myCatalog.length ] = new Product(code, name, type);
}

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 
		pInfo 		  = cart[i].split(",");
		thisProd 		= findProductInCatalog(pInfo[0]);
		myCart[ i ] = new CartItem(pInfo[0], thisProd.name, thisProd.weight, pInfo[1], pInfo[2], pInfo[3], pInfo[4], pInfo[5]);
	}
}

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 ].price + "," + myCart[ i ].size + "," + myCart[ i ].fabric + "," + myCart[ i ].qty + "," + myCart[ i ].option1;
	}	
	writeCookie("cart", cart, 24);	
}

function addItemToCart(form, code, size, fabric, price, qty, option1) {
	// If price not supplied, retrieve price from value variable of size selection box.
	var q = "";
	var s = "";
	var f = "";
	var p = "";
	var o = "";
	var obj = "";
	
	if (price == "") {
		p = ( (eval("form."+size) != null) ? eval("form."+size+".options[form."+size+".selectedIndex].value"):"" );
	} else {
		p = ( (eval("form."+price) != null) ? eval("form."+price+".value"):"" );
	}
	
	// Get reference to product object from catalog
	var thisProd = findProductInCatalog(code);
	
	// Add Product to Cart 
	if (thisProd) {
		// Retrieve Values from selection boxes
		if (eval("form."+size+".type") == "hidden") {
			s = ( (eval("form."+size) != null) ? eval("form."+size+".value"):" " );			
		} else {
			s = ( (eval("form."+size) != null) ? eval("form."+size+".options[form."+size+".selectedIndex].text"):" " );			
		}
		q = ( (eval("form."+qty) != null) ? eval("form."+qty+".options[form."+qty+".selectedIndex].text"):"" );
		
		// Get value of fabric radiobox
		obj = ( (eval("form."+fabric) != null) ? eval("form."+fabric):"" );
		if (obj) {
			if (obj.length == null) { 
				f = String(obj.value);
			} else {
				for (var i=0; i < obj.length; i++) {
					if (obj[i].checked)f = String(obj[i].value);
				}
			}
		}

		// Get value of checkbox if checked
		if (option1 != "") {
			o = ( (eval("form."+option1) != null) ? eval("form."+option1+".options[form."+option1+".selectedIndex].value"):" " );			
		}
		myCart[ myCart.length ] = new CartItem(code, thisProd.name, thisProd.weight, p, s, f, q, o);
	}	
	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();	
}

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;	
}

//----------------------------------------------------------------
// Calc Cart Total Costs 

function calcCartPriceGST() {
	for (var i = 0; i < myCart.length; i++) {
			totalProd += myCart[i].price * myCart[i].qty;
			totalWeight += myCart[i].weight * myCart[i].qty;
	}
	if (totalWeight <= 35) {
			totalPostage = 4.10;
	} else if (totalWeight <=500) {
			totalPostage = 8;
	} else if (totalWeight > 500 && totalWeight <= 3000) {
			totalPostage = 11;
	} else if (totalWeight > 3000 && totalWeight <= 5000) {
			totalPostage = 18;
	} else {
		strErrorMsg = "Your order is over 5kg.  Please contact us for shipping costs."
	}

	numItems = myCart.length;
	totalGST = parseFloat(parseFloat(totalProd+totalPostage) / 11).toFixed(2);

}

//----------------------------------------------------------------
// View Cart functions
function getCartPageHTML() {
	var strHTML = "";
	
	if (myCart.length > 0) {
		for (var i = 0; i < myCart.length; i++) {
			strHTML += "<tr >";
			strHTML += '	<td align="right" bgcolor="#F3ECE4" nowrap>';
			strHTML += '     <input name="q'+i+'" type="text" id="q'+i+'" size="3" value="'+myCart[i].qty+'">';
			strHTML += "     <input type=\"button\" name=\"change\" value=\"Change\" onclick=\"updateItemInCart("+i+",this.form,'q"+i+"');refreshPage();\"/>";			
			strHTML += '  </td>';
			strHTML += '  <td bgcolor="#F3ECE4">'+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="#F3ECE4">'+myCart[i].fabric+' '+myCart[i].option1+'<input name="fabric'+i+'" type="hidden" id="fabric'+i+'" value="'+myCart[i].fabric+' '+myCart[i].option1+'" /></td>'
			strHTML += '	<td align="center" bgcolor="#F3ECE4">'+myCart[i].size+'<input name="size'+i+'" type="hidden" id="size'+i+'" value="'+myCart[i].size+'" /></td>'
			strHTML += '	<td align="right" bgcolor="#F3ECE4">$'+parseFloat(myCart[i].price).toFixed(2)+'<input name="price'+i+'" type="hidden" id="price'+i+'" value="'+myCart[i].price+'" /></td>';
			strHTML += '	<td align="right" bgcolor="#F3ECE4">$';
			strHTML +=    parseFloat(myCart[i].price * myCart[i].qty).toFixed(2);
			strHTML += '  <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="#F3ECE4" ><input type="button" name="Button" value="Clear Order" onclick="clearOrder();refreshPage();"/></td>';
		strHTML += '      <td bgcolor="#F3ECE4" >&nbsp;</td>';
		strHTML += '      <td bgcolor="#F3ECE4" >&nbsp;</td>';
		strHTML += '      <td bgcolor="#F3ECE4" >&nbsp;</td>';
		strHTML += '      <td bgcolor="#F3ECE4" >&nbsp;</td>';
		strHTML += '      <td bgcolor="#F3ECE4" >&nbsp;</td>';
		strHTML += '    </tr>';
	} else {
		strHTML += '<tr><td colspan="6"><strong class="textWhite">Your basket is empty</strong></td></tr>'
	}
	return strHTML;
}

function getCartOrderPageHTML() {
	var strHTML = "";
	for (var i = 0; i < myCart.length; i++) {
		strHTML += "<tr >";
		strHTML += '  <td class="tdrb">'+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 class="tdrb">'+myCart[i].fabric+'<input name="fabric'+i+'" type="hidden" id="fabric'+i+'" value="'+myCart[i].fabric+' '+myCart[i].option1+'" /></td>'
		strHTML += '	<td align="center" class="tdrb">'+myCart[i].size+'<input name="size'+i+'" type="hidden" id="size'+i+'" value="'+myCart[i].size+'" /></td>'
		strHTML += '	<td align="center" class="tdrb">'+myCart[i].qty+'<input name="q'+i+'" type="hidden" id="q'+i+'" size="3" value="'+myCart[i].qty+'"></td>'
		strHTML += '	<td align="right" class="tdrb">$'+parseFloat(myCart[i].price).toFixed(2)+'<input name="price'+i+'" type="hidden" id="price'+i+'" value="'+myCart[i].price+'" /></td>';
		strHTML += '	<td align="right" class="tdb">$';
		strHTML +=    parseFloat(myCart[i].price * myCart[i].qty).toFixed(2);
		strHTML += '  <input name="ptotal'+i+'" type="hidden" id="ptotal'+i+'" value="'+parseFloat(myCart[i].price * myCart[i].qty).toFixed(2)+'" />';
		strHTML += '</tr>';
	}
	strHTML += '	<input name="numProducts" type="hidden" id="numProducts" value="'+myCart.length+'" /></td>'

	return strHTML;
}

function getCartProductPriceHTML() {
	var strHTML = "";
	strHTML += '<input name="oProduct" type="hidden" id="oProduct" value="'+ parseFloat(totalProd).toFixed(2) +'" />';
	strHTML += "$" + totalProd.toFixed(2);
	
	return strHTML;
}

function getCartGstHTML() {
	var strHTML = "";
	strHTML += '<input name="oGST" type="hidden" id="oGST" value="'+ parseFloat(totalGST).toFixed(2) +'" />';
	strHTML += "$" + parseFloat(totalGST).toFixed(2);
	
	return strHTML;
}

function getCartWeightHTML() {
	var strHTML = "Total Order Weight (for postage): ";
	
	if (totalWeight < 1000) {
		strHTML += 	parseFloat(totalWeight) + "g";
	} else {
		strHTML += 	parseFloat(totalWeight/1000.00).toFixed(2) + "kg";
	}
	return strHTML;
}

function getCartPostageHTML() {
	var strHTML = "";
	
	strHTML += '<input name="oPostage" type="hidden" id="oPostage" value="'+ parseFloat(totalPostage).toFixed(2) +'" />$';
	strHTML += 	parseFloat(totalPostage).toFixed(2);
	return strHTML;
}

function getCartTotalPriceHTML() {
	var strHTML = "";
	
	var total = parseFloat(totalProd) + parseFloat(totalPostage);
	strHTML += '<input name="oTotal" type="hidden" id="oTotal" value="'+ parseFloat(total).toFixed(2) +'" />$';
	strHTML += 	parseFloat(total).toFixed(2);	
	return strHTML;
}


function getCheckoutBtnOrErrMsgHTML() {
	var strMsg = "";
	var strHTML = "";
	
	if (strErrorMsg != "") {
		strMsg += strErrorMsg;
	}
	if (numItems == 0) {
		strMsg += "Please add one of our wonderful products to your shopping basket.";	
	}
	
	if (strMsg != "") {
		strHTML = '<tr><td colspan="3" align="right" bgcolor="#CEAE8E"><strong class="textWhite">'+strMsg+'</strong></td></tr>';
	} else {
    strHTML = '<tr><td colspan="3" align="right" bgcolor="#CEAE8E">';
		strHTML += '<input name="imageField" type="image" src="../images/btn_checkout.gif" alt="Proceed to secure checkout" width="154" height="20" border="0" ></td></tr>';
	}
	
	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('326', '326 Swimsuit', '250');
addToCatalog('328', '328 Swimsuit', '250');
addToCatalog('335', '335 Swimsuit', '250');
addToCatalog('368', '368 Swimsuit', '250');
addToCatalog('325', '325 Swimsuit', '250');
addToCatalog('323', '323 Swimsuit', '250');
addToCatalog('456', '456 Swimshirt', '250');
addToCatalog('Bike Shorts', 'Bike Shorts', '100');
addToCatalog('20mm wide elastic', '20mm wide elastic', '13');
addToCatalog('Bra Tubing', 'Bra Tubing', '9');
addToCatalog('Shelf bra elastic 20mm wide', 'Shelf bra elastic 20mm wide', '9');
addToCatalog('Soft bra cup', 'Soft bra cup', '7');
addToCatalog('Bra wires', 'Bra wires', '13');
addToCatalog('Bikini clips', 'Bikini clips', '1');
addToCatalog('38mm wide elastic', '38mm wide elastic', '26');
addToCatalog('12mm wide elastic', '12mm wide elastic', '7');
addToCatalog('9mm wide clear swimwear elastic', '9mm wide clear swimwear elastic', '2.5');
addToCatalog('6mm wide elastic', '6mm wide elastic', '4');
addToCatalog('Fabric Print', 'Fabric Print', '250');
addToCatalog('Fabric Plain', 'Fabric Plain', '250');
addToCatalog('Lining', 'Lining', '180');

// Read Saved Cart Items from Cookie
createCartFromCookie();

// Calculate current order total and gst
calcCartPriceGST();

