var merchTotal = 0.00;
var discount = 0.00;
var grandTotal = 0.00;
var shipMethods = new Array();
var labelFmt = "Estimated Shipping via {shipMethod}";
var shipHeaderFmt = "ESTIMATE WITH {shipMethod}";
var curShipId = null;

/**
* Represents a shipping method
*/
function shipMethod(shipId, shipLabel, shipDescription, shipAmount) {
	this.shipId = shipId;
	this.shipLabel = shipLabel;
	this.shipDescription = shipDescription;
	this.shipAmount = shipAmount;
}

function changeShipMethod(shipId, shipHeaderLabelElementId, shipLabelElementId, shipAmtElementId, totalElementId, freeShip) {
	curShipId = shipId;
	var curMethod = shipMethods[shipId];
	if(curMethod != null) {
		var shipMethodLabel = curMethod.shipLabel;
		var newGrandTotal = formatCurrency(merchTotal - discount + curMethod.shipAmount);
		var shipLabel = labelFmt.replace("{shipMethod}", shipMethodLabel);
		if (shipMethodLabel.replace(/^\s+|\s+$/g,"") == "USPS") {
			shipMethodLabel = "USPS STANDARD";
		}
		var shipHeader = shipHeaderFmt.replace("{shipMethod}", shipMethodLabel.toUpperCase());
		if (freeShip) {
			shipLabel = "Free Shipping";
			shipHeader = "FREE SHIPPING";
		}
		document.getElementById(shipAmtElementId).innerHTML = formatCurrency(curMethod.shipAmount);
		document.getElementById(totalElementId).innerHTML = newGrandTotal;
		document.getElementById(shipLabelElementId).innerHTML = shipLabel;
		document.getElementById(shipHeaderLabelElementId).innerHTML = shipHeader;
	}
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}