
function format_money(val){

	var money_value = "$" + val;
	var point = money_value.indexOf(".");
	var strlen = money_value.length;

	if (point == -1){
		money_value = money_value + ".00";
	} else {
		if (strlen - point > 3){
			trunc = point + 3;
			money_value = money_value.substring(0, trunc);
		}
		if (money_value.length - point == 2)
			money_value = money_value + "0";
	}
	return(money_value);
}

function add_money(val1, val2){
	re = /^\$|,/g;
	val1 = val1.replace(re, "");
	val2 = val2.replace(re, "");	
	return(format_money(parseFloat(val1) + parseFloat(val2)));

}


function calc_freight(qty){
	freight = 0;
	if (qty){
		freight = 20;
		if (qty >= 6 && qty <=15){
			freight = 10;
		}
		if (qty < 6){
			freight = 6.5;
		}
	}
	return(freight);
}


function total_fields(fieldnames, qty, total, price){
	itemqty = 0;
	for (c=0; c<fieldnames.length;c++){
		f = fieldnames[c];
		if (document.ShoppingCartForm[f].value)	itemqty = itemqty + parseInt(document.ShoppingCartForm[f].value);
	}

	document.ShoppingCartForm[qty].value = itemqty;
	document.ShoppingCartForm[total].value = format_money(itemqty * price);	
	grand_total();

}

function stock_check(ordered, instock){
	if (parseInt(ordered) > parseInt(instock)){
		alert("You have ordered more items than we have left in stock (" + instock + ")");
	}
}

function grand_total(){
	itemqty = 0;
	tv = "$0.00";
	for (c=0; c<atotalqty.length;c++){
		f = atotalqty[c];
		if (document.ShoppingCartForm[f].value)	itemqty = itemqty + parseInt(document.ShoppingCartForm[f].value);
	}

	for (c=0; c<atotal.length;c++){
		f = atotal[c];
		v = document.ShoppingCartForm[f].value;
		tv = add_money(tv, v);
	}
	freight = format_money(calc_freight(itemqty));
	gst_total = format_money(add_gst(tv));
	gtv = add_money(gst_total, freight);
	large_order_check(itemqty);	
	document.ShoppingCartForm["Gst"].value = format_money(gst_component(gst_total));	
	document.ShoppingCartForm["TotalQty"].value = itemqty;	
	document.ShoppingCartForm["Freight"].value = freight;
	document.ShoppingCartForm["TotalValue"].value = gtv;	

}


function add_gst(value){
	re = /^\$|,/g;
	value = value.replace(re, "");

	var gstvalue = parseFloat(value) * 1.15;
	gstvalue = Math.ceil(gstvalue * 100) / 100;
	return(gstvalue);
}


function gst_component(value){
	re = /^\$|,/g;
	value = value.replace(re, "");
	gst = parseFloat(value) * 3 / 23;
	gst = Math.floor(gst * 100) / 100;

	return(gst);
	
}

var large_order_text = "You have ordered more than 50 garments.  This may quality you for bulk discount, please call 09 3580114 to discuss";
var lod = false;
function large_order_check(value){
	if (lod) return;
	if (value > 50){
		alert(large_order_text);
		lod = true;
	}
	return;
}
