var CART_SELECTIONS_KEY = 'cartSelectionsKey';
var CART_SHIPPING_LOCATION_KEY = 'cartShippingLocation';
var CART_PAYMENT_METHOD_KEY = 'cartPaymentMethod';
var CART_QUANTITY_KEY_PREFIX = 'cartQuantity';
var CART_EXPIRATION_WEEKS = 3;
var MAIL_ORDER_SELECTIONS_KEY = 'mailOrderSelectionsKey';
var MAIL_ORDER_SHIPPING_LOCATION_KEY = 'mailOrderShippingLocation';
var MAIL_ORDER_PAYMENT_METHOD_KEY = 'mailOrderPaymentMethod';
var MAIL_ORDER_EXPIRATION_WEEKS = 1;
var today = new Date();
var wayBackWhen = new Date(today.getTime() - 500 * 7 * 24 * 60 * 60 * 1000);
var cartExpirationDate = new Date(today.getTime() + CART_EXPIRATION_WEEKS * 7 * 24 * 60 * 60 * 1000);
var mailOrderExpirationDate = new Date(today.getTime() + MAIL_ORDER_EXPIRATION_WEEKS * 7 * 24 * 60 * 60 * 1000);

/*-- Start ShippingRate --------------------------------------------------------------------------*/

function ShippingRate(location, rate)
{
	this.setLocation = ShippingRate_setLocation;
	this.getLocation = ShippingRate_getLocation;
	this.setLocation(location);
	
	this.setRate = ShippingRate_setRate;
	this.getRate = ShippingRate_getRate;
	this.setRate(rate);
	
	return this;
}

function ShippingRate_setLocation(location)
{
	this.location = location;
}

function ShippingRate_getLocation()
{
	return this.location;
}

function ShippingRate_setRate(rate)
{
	this.rate = rate;
}

function ShippingRate_getRate()
{
	return this.rate;
}

/*-- End ShippingRate ----------------------------------------------------------------------------*/

/*-- Start Cart ----------------------------------------------------------------------------------*/

function Cart()
{
	this.initialize = Cart_initialize;
	
	this.persist = Cart_persist;
	
	this.displayEditable = Cart_displayEditable;
	this.displayReadOnly = Cart_displayReadOnly;
	this.displayReadOnlyCheckOut = Cart_displayReadOnlyCheckOut;
	this.displayReadOnlyMailOrder = Cart_displayReadOnlyMailOrder;
	this.displayEditableCheckOut = Cart_displayEditableCheckOut;
	this.displayCheckOutButton = Cart_displayCheckOutButton;
	
	this.writePayPalForm = Cart_writePayPalForm;
	this.writeMailOrderForm = Cart_writeMailOrderForm;

	this.saveMailOrder = Cart_saveMailOrder;
	
	this.isEmpty = Cart_isEmpty;
	
	this.updateFromPage = Cart_updateFromPage;
	
	this.refreshPage = Cart_refreshPage;
	
	this.setSelections = Cart_setSelections;
	this.getSelections = Cart_getSelections;
	this.setSelections(null);
	
	this.getMailOrderSelections = Cart_getMailOrderSelections;

	this.addSelection = Cart_addSelection;
	
	this.removeSelection = Cart_removeSelection;
	
	this.removeAllSelections = Cart_removeAllSelections;
	
	// If the rates are changed, update database.txt too
	var shippingRates = new Array();
	shippingRates[0] = new ShippingRate("Continental United States", 5.00);
	shippingRates[1] = new ShippingRate("Alaska and Hawaii", 7.00);
	shippingRates[2] = new ShippingRate("Canada", 19.00);
	shippingRates[3] = new ShippingRate("Europe", 26.00);
	shippingRates[4] = new ShippingRate("Australia", 25.00);
	shippingRates[5] = new ShippingRate("New Zealand", 25.00);
	
	this.setShippingRates = Cart_setShippingRates;
	this.getShippingRates = Cart_getShippingRates;
	this.setShippingRates(shippingRates);

	this.setShippingLocation = Cart_setShippingLocation;
	this.getShippingLocation = Cart_getShippingLocation;
	this.setShippingLocation(shippingRates[0].getLocation());
	
	this.getShippingRate = Cart_getShippingRate;

	this.setPaymentMethod = Cart_setPaymentMethod;
	this.getPaymentMethod = Cart_getPaymentMethod;
	this.setPaymentMethod("PayPal");
	
	return this;
}

function Cart_initialize()
{
    // Get the customer's selections
    var rawSelections = getCookie(CART_SELECTIONS_KEY);
	if (rawSelections == null)
	{
	    return;
	}
    
    // Parse out the selections
	var selectionArray = rawSelections.split('-->');
	var selections = new Array(selectionArray.length);
	for (var i = 0; i < selectionArray.length; i++)
	{
	    var selection = selectionArray[i].split('::');
		selections[i] = new CartSelection(selection[0], parseInt(selection[1]));
	}
	
	this.setSelections(selections);
	
	// Get the shipping location
	var location = getCookie(CART_SHIPPING_LOCATION_KEY);
	if (location != null)
	{
		this.setShippingLocation(location);
	}

	// Get the payment method
	var paymentMethod = getCookie(CART_PAYMENT_METHOD_KEY);
	if (paymentMethod != null)
	{
		this.setPaymentMethod(paymentMethod);
	}
}

function Cart_persist()
{
	var selections = this.getSelections();
	if (selections == null)
	{
		setCookie(CART_SELECTIONS_KEY, null, wayBackWhen, "/");
		return;
	}
	
    // Create a string containing the customer's selections
    var rawSelections = '';
    for (var i = 0; i < selections.length; i++)
	{
        if (selections[i] != null)
		{
            rawSelections += selections[i].getId() +
                             "::" +
                             selections[i].getQuantity() +
                             "-->";
		}
	}
    
    // Trim off the last "-->"
    if (rawSelections.length > 0)
	{
        rawSelections = rawSelections.substring(0, rawSelections.length - 3);
	}
        
    // Track the selections via a cookie
    setCookie(CART_SELECTIONS_KEY, rawSelections, cartExpirationDate, "/");
	
	// Track the shipping location via a cookie
	setCookie(CART_SHIPPING_LOCATION_KEY, this.getShippingLocation(), cartExpirationDate, "/");
	
	// Track the payment method via a cookie
	setCookie(CART_PAYMENT_METHOD_KEY, this.getPaymentMethod(), cartExpirationDate, "/");
}

function Cart_saveMailOrder()
{
	var selections = this.getSelections();
	if (selections == null)
	{
		setCookie(CART_SELECTIONS_KEY, null, wayBackWhen, "/");
		return;
	}
	
    // Create a string containing the customer's selections
    var rawSelections = '';
    for (var i = 0; i < selections.length; i++)
	{
        if (selections[i] != null)
		{
            rawSelections += selections[i].getId() +
                             "::" +
                             selections[i].getQuantity() +
                             "-->";
		}
	}
    
    // Trim off the last "-->"
    if (rawSelections.length > 0)
	{
        rawSelections = rawSelections.substring(0, rawSelections.length - 3);
	}
        
    // Track the selections via a cookie
    setCookie(MAIL_ORDER_SELECTIONS_KEY, rawSelections, mailOrderExpirationDate, "/");
	
	// Track the shipping location via a cookie
	setCookie(MAIL_ORDER_SHIPPING_LOCATION_KEY, this.getShippingLocation(), mailOrderExpirationDate, "/");
	
	// Track the payment method via a cookie
	setCookie(MAIL_ORDER_PAYMENT_METHOD_KEY, this.getPaymentMethod(), mailOrderExpirationDate, "/");
}

function Cart_isEmpty()
{
	var selections = this.getSelections();
	return selections == null || selections.length == 0;
}

function Cart_setSelections(selections)
{
	this.selections = selections;
}

function Cart_getSelections()
{
	return this.selections;
}

function Cart_addSelection(selection)
{
	var selections = this.getSelections();
	if (this.isEmpty())
	{
		selections = new Array();
		selections[0] = selection;
	}
	else
	{
		selections[selections.length] = selection;
	}
	
	this.setSelections(selections);
}

function Cart_removeSelection(id)
{
    if (this.isEmpty())
	{
        return;
	}
    var selections = this.getSelections();
	var numSelections = 0;
    for (var i = 0; i < selections.length; i++)
    {
		if (id == selections[i].getId())
		{
			delete selections[i];
		}
		else
		{
			numSelections++;
		}
    }
	if (numSelections == 0)
	{
		selections = null;
	}
    this.setSelections(selections);	
    
	this.persist();
	
    //
    // Go to Shopping Cart
    //
    //document.location = "../shopping/index.html";
	window.location.reload();
}

function Cart_removeAllSelections()
{
	this.setSelections(null);
	
	this.persist();
}

function Cart_getMailOrderSelections()
{
    // Get the customer's selections
    var rawSelections = getCookie(MAIL_ORDER_SELECTIONS_KEY);
	if (rawSelections == null)
	{
	    return;
	}
    
    // Parse out the selections
	var selectionArray = rawSelections.split('-->');
	var selections = new Array(selectionArray.length);
	for (var i = 0; i < selectionArray.length; i++)
	{
	    var selection = selectionArray[i].split('::');
		selections[i] = new CartSelection(selection[0], parseInt(selection[1]));
	}
	
	return selections;
}

function Cart_setShippingRates(shippingRates)
{
	this.shippingRates = shippingRates;
}

function Cart_getShippingRates()
{
	return this.shippingRates;
}

function Cart_setShippingLocation(shippingLocation)
{
	this.shippingLocation = shippingLocation;
}

function Cart_getShippingLocation()
{
	return this.shippingLocation;
}

function Cart_getShippingRate()
{
	var rate = 0.0;
	var rates = this.getShippingRates();
	var location = this.getShippingLocation();
	for (var i = 0; i < rates.length; i++)
	{
		if (rates[i].getLocation() == location)
		{
			rate = rates[i].getRate();
			break;
		}
	}

	return rate;
}

function Cart_setPaymentMethod(paymentMethod)
{
	this.paymentMethod = paymentMethod;
}

function Cart_getPaymentMethod()
{
	return this.paymentMethod;
}

function Cart_displayEditable()
{
	var selections = this.getSelections();
    if (this.isEmpty())
	{
        document.writeln('<table id="shoppingCartEmpty" border="0" cellspacing="0" cellpadding="0" width="100%">' +
                           '<tr>' +
						     '<td id="heading" style="padding-top:20px" colspan="3">Your shopping cart is empty.</td>' +
						   '</tr>' +
                           '<tr>' +
						     '<td height="20" colspan="3" style="text-align:center"><img src="../images/dividerMedium.gif" width="420" height="1" alt=""></td>' +
						   '</tr>' +
                           '<tr>' +
						     '<td height="20" colspan="3" style="padding: 12px 3px 0px 20px">Your shopping cart is empty for one of the following reasons:</td>' +
						   '</tr>' +
                           '<tr>' +
							 '<td width="15" align="center">&nbsp;</td>' +
                             '<td width="15" align="center" valign="top" style="padding: 21px 3px 0px 3px"><img src="../images/bullet.gif" width="7" height="9" align="absmiddle"></td>' +
							 '<td valign="top" style="padding: 18px 3px 0px 3px">You have not selected the <em>Add to Cart</em> button on any of the product pages.</td>' +
						   '</tr>' +
                           '<tr>' +
							 '<td width="15" align="center">&nbsp;</td>' +
                             '<td width="15" align="center" valign="top" style="padding: 21px 3px 0px 3px"><img src="../images/bullet.gif" width="7" height="9" align="absmiddle"></td>' +
							 '<td valign="top" style="padding: 18px 3px 0px 3px">You have removed all items from your shopping cart by selecting the <em>remove</em> link for all items or by specifying <em>0</em> as the quantity for all items, followed by pressing the <em>Update Cart</em> button.</td>' +
						   '</tr>' +
                           '<tr>' +
							 '<td width="15" align="center">&nbsp;</td>' +
                             '<td width="15" align="center" valign="top" style="padding: 21px 3px 0px 3px"><img src="../images/bullet.gif" width="7" height="9" align="absmiddle"></td>' +
							 '<td valign="top" style="padding: 18px 3px 0px 3px">You have turned off Web browser cookies.  Cookies are necessary for shopping on the Myles Pinkney Online Gallery.  To learn more about cookies, see our <a href="../common/cookies.html">cookies</a> page.</td>' +
						   '</tr>' +
                           '<tr>' +
							 '<td width="15" align="center">&nbsp;</td>' +
                             '<td width="15" align="center" valign="top" style="padding: 21px 3px 0px 3px"><img src="../images/bullet.gif" width="7" height="9" align="absmiddle"></td>' +
							 '<td valign="top" style="padding: 18px 3px 0px 3px">You have specified that JavaScript&trade; may not be executed in your Web browser. Without the use of Javascript&trade;, many pages on this site will not function properly.</td>' +
						   '</tr>' +
                           '<tr>' +
						     '<td height="20" colspan="3" style="padding: 18px 3px 20px 20px">If you believe your shopping cart should contain items, please <a href="../contact/contactUs.html">contact us</a>.</td>' +
						   '</tr>' +
						  '</table>'
						);
	}
    else
    {
		if (productSet == null)
		{
			productSet = new ProductSet();
		}
		
		var html = '';
		html +=
		'<table id="shoppingCart" border="0" cellspacing="0" cellpadding="0" width="500">' +
			'<tr>' +
				'<th id="quantity" class="string">Quantity</th>' +
				'<th id="description" class="string">Description</th>' +
				'<th id="each" class="numeric">Each</th>' + 
				'<th id="total" class="numeric">Total</th>' +
				'<th id="remove" class="action">&nbsp;</th>' +
			'</tr>';
        var subtotal = 0.0;
		var price = 0.0;
	    for (var i = 0; i < selections.length; i++)
	    {
	        var product = productSet.getProduct(selections[i].getId());
	        html +=
			'<tr>' +
				'<td class="control">' +
					'<input' +
						' class="textField"' +
						' type="text"' +
						' id="' + CART_QUANTITY_KEY_PREFIX + selections[i].getId() + '"' +
						' size="3"' +
						' value="' + selections[i].getQuantity() + '"' +
					'>' +
				'</td>' +
				'<td class="string">' +
					'<a' +
						' href="' + product.getUrl() + '"' +
						' onMouseOver="window.status=\'See more information about this print\';return true;"' +
						' onMouseOut="window.status=\'\'">' +
						product.getDescription() +
					'</a>' +
				'</td>';
			price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
			html +=
				'<td class="numeric">' + formatCurrency(price) + '</td>' + 
				'<td class="numeric">' + formatCurrency(price * selections[i].getQuantity()) + '</td>' +
				'<td class="action">' +
					'<a href="javascript:removeShoppingCartSelection(\'' + selections[i].getId() + '\')">remove</a>' +
				'</td>' +
			'</tr>';
            subtotal += price * selections[i].getQuantity();
        }
		
		html +=
			'<tr>' +
				'<td id="updateCartContainer" colspan="2"><a id="updateCart" href="javascript:updateShoppingCart()"><img src="../images/blank.gif" alt="Click to update your shopping cart if you\'ve changed any quantities" title="Click to update your shopping cart if you\'ve changed any quantities" name="buttonUpdateCart" id="buttonUpdateCart"></a><span>if you changed quantities</span></td>' +
				'<td id="subtotalLabel">Subtotal:</td>'+
				'<td id="subtotalValue">' + formatCurrency(subtotal) + '</td>' +
				'<td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="shippingLabel" colspan="3">' +
					'Shipping to ' +
					'<select id="shippingLocation" class="selectNormal" onchange="javascript:shippingLocationChanged(this)">';
					var rates = this.getShippingRates();
					for (var i = 0; i < rates.length; i++)
					{
						if (rates[i].getLocation() == this.getShippingLocation())
						{
							html +=
							'<option selected="selected" value="' + rates[i].getLocation() + '">' + rates[i].getLocation() + '</option>';
						}
						else
						{
							html +=
							'<option value="' + rates[i].getLocation() + '">' + rates[i].getLocation() + '</option>';
						}						
					}
					html +=
					'</select>:' +
				'</td>';
				var rate = this.getShippingRate();
				html +=
				'<td id="shippingValue">' + formatCurrency(rate) + '</td>' +
				'<td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="totalLabel" colspan="3">Total:</td>' +
				'<td id="totalValue">US&nbsp;' + formatCurrency(subtotal + rate) + '</td>' +
				"<td>&nbsp;</td>" +
			'</tr>' +
		'</table>';
		
		//document.getElementById("tmp").value = html;
		
		document.write(html);
    }
}

function Cart_displayEditableCheckOut()
{
	var selections = this.getSelections();
    if (this.isEmpty())
	{
		document.location = "index.html";
	}
    else
    {
		if (productSet == null)
		{
			productSet = new ProductSet();
		}
		
		var html = '';
		html +=
		'<table id="shoppingCart" border="0" cellspacing="0" cellpadding="0" width="500">' +
			'<tr>' +
				'<th id="quantity" class="string">Quantity</th>' +
				'<th id="description" class="string">Description</th>' +
				'<th id="each" class="numeric">Each</th>' + 
				'<th id="total" class="numeric">Total</th>' +
				'<th id="remove" class="action">&nbsp;</th>' +
			'</tr>';
        var subtotal = 0.0;
		var price = 0.0;
	    for (var i = 0; i < selections.length; i++)
	    {
	        var product = productSet.getProduct(selections[i].getId());
			price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
	        html +=
			'<tr>' +
				'<td class="control">' +
					'<input' +
						' class="textField"' +
						' type="text"' +
						' id="' + CART_QUANTITY_KEY_PREFIX + selections[i].getId() + '"' +
						' size="3"' +
						' value="' + selections[i].getQuantity() + '"' +
					'>' +
				'</td>' +
				'<td class="string">' +
					product.getDescription() +
				'</td>' +
				'<td class="numeric">' + formatCurrency(price) + '</td>' + 
				'<td class="numeric">' + formatCurrency(price * selections[i].getQuantity()) + '</td>' +
				'<td class="action">' +
					'<a href="javascript:removeShoppingCartSelection(\'' + selections[i].getId() + '\')">remove</a>' +
				'</td>' +
			'</tr>';
            subtotal += price * selections[i].getQuantity();
        }
		
		html +=
			'<tr>' +
				'<td id="updateCartContainer" colspan="2"><a id="updateCart" href="javascript:updateShoppingCart()"><img src="../images/blank.gif" alt="Click to update your shopping cart if you\'ve changed any quantities" title="Click to update your shopping cart if you\'ve changed any quantities" name="buttonUpdateCart" id="buttonUpdateCart"></a><span>if you changed quantities</span></td>' +
				'<td id="subtotalLabel">Subtotal:</td>'+
				'<td id="subtotalValue">' + formatCurrency(subtotal) + '</td>' +
				'<td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="shippingLabel" colspan="3">' +
					'Shipping to ' +
					'<select id="shippingLocation" class="selectNormal" onchange="javascript:shippingLocationChanged(this)">';
					var rates = this.getShippingRates();
					for (var i = 0; i < rates.length; i++)
					{
						if (rates[i].getLocation() == this.getShippingLocation())
						{
							html +=
							'<option selected="selected" value="' + rates[i].getLocation() + '">' + rates[i].getLocation() + '</option>';
						}
						else
						{
							html +=
							'<option value="' + rates[i].getLocation() + '">' + rates[i].getLocation() + '</option>';
						}						
					}
					html +=
					'</select>:' +
				'</td>';
				var rate = this.getShippingRate();
				html +=
				'<td id="shippingValue">' + formatCurrency(rate) + '</td>' +
				'<td>&nbsp;</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="totalLabel" colspan="3">Total:</td>' +
				'<td id="totalValue">US&nbsp;' + formatCurrency(subtotal + rate) + '</td>' +
				"<td>&nbsp;</td>" +
			'</tr>' +
		'</table>';
		
		//document.getElementById("tmp").value = html;
		
		document.write(html);
    }
}

function Cart_displayCheckOutButton()
{
	if (!this.isEmpty())
	{
		document.write('<tr><td align="right" class="checkOutButtonContainer"><a href="checkOut_selectPaymentMethod.html" class="buttonCheckOut"><img src="../images/blank.gif" alt="Complete your order" title="Complete your order"></a></td></tr>');
	}
}

function Cart_displayReadOnly()
{
	var selections = this.getSelections();
	if (productSet == null)
	{
		productSet = new ProductSet();
	}
		
    if (this.isEmpty())
	{
        document.writeln('<table id="shoppingCartEmpty" border="0" cellspacing="0" cellpadding="0" width="100%">' +
                           '<tr>' +
						     '<td id="heading" colspan="3">Your shopping cart is empty.</td>' +
						   '</tr>' +
						  '</table>');
	}
	else
	{
		var html = '';
		html +=
		'<table id="shoppingCart" border="0" cellspacing="0" cellpadding="0" width="500">' +
			'<tr>' +
				'<th id="quantity" class="string">Quantity</th>' +
				'<th id="description" class="string">Description</th>' +
				'<th id="each" class="numeric">Each</th>' + 
				'<th id="total" class="numeric">Total</th>' +
			'</tr>';
        var subtotal = 0.0;
		var price = 0.0;
	    for (var i = 0; i < selections.length; i++)
	    {
	        var product = productSet.getProduct(selections[i].getId());
			price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
	        html +=
			'<tr>' +
				'<td class="string">' +
					selections[i].getQuantity() +
				'</td>' +
				'<td class="string">' +
					product.getDescription() +
				'</td>' +
				'<td class="numeric">' + formatCurrency(price) + '</td>' + 
				'<td class="numeric">' + formatCurrency(price * selections[i].getQuantity()) + '</td>' +
			'</tr>';
            subtotal += price * selections[i].getQuantity();
        }
		
		html +=
			'<tr>' +
				'<td id="subtotalLabel" colspan="3">Subtotal:</td>'+
				'<td id="subtotalValue">' + formatCurrency(subtotal) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="shippingLabel" colspan="3">' +
					'Shipping (' + this.getShippingLocation() + '):' +
				'</td>';
				var rate = this.getShippingRate();
				html +=
				'<td id="shippingValue">' + formatCurrency(rate) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="totalLabel" colspan="3">Total:</td>' +
				'<td id="totalValue">US&nbsp;' + formatCurrency(subtotal + rate) + '</td>' +
			'</tr>' +
		'</table>';
		
		//document.getElementById("tmp").value = html;
		
		document.write(html);
	}
}

function Cart_displayReadOnlyMailOrder()
{
	if (productSet == null)
	{
		productSet = new ProductSet();
	}
		
	var selections = this.getMailOrderSelections();
    if (selections == null)
	{
        document.writeln('<table id="shoppingCartEmpty" border="0" cellspacing="0" cellpadding="0" width="100%">' +
                           '<tr>' +
						     '<td id="heading" colspan="3">Your shopping cart is empty.</td>' +
						   '</tr>' +
						  '</table>');
	}
	else
	{
		var html = '';
		html +=
		'<table id="shoppingCart" border="0" cellspacing="0" cellpadding="0" width="500">' +
			'<tr>' +
				'<th id="quantity" class="string">Quantity</th>' +
				'<th id="description" class="string">Description</th>' +
				'<th id="each" class="numeric">Each</th>' + 
				'<th id="total" class="numeric">Total</th>' +
			'</tr>';
        var subtotal = 0.0;
		var price = 0.0;
	    for (var i = 0; i < selections.length; i++)
	    {
	        var product = productSet.getProduct(selections[i].getId());
			price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
	        html +=
			'<tr>' +
				'<td class="string">' +
					selections[i].getQuantity() +
				'</td>' +
				'<td class="string">' +
					product.getDescription() +
				'</td>' +
				'<td class="numeric">' + formatCurrency(price) + '</td>' + 
				'<td class="numeric">' + formatCurrency(price * selections[i].getQuantity()) + '</td>' +
			'</tr>';
            subtotal += price * selections[i].getQuantity();
        }
		
		html +=
			'<tr>' +
				'<td id="subtotalLabel" colspan="3">Subtotal:</td>'+
				'<td id="subtotalValue">' + formatCurrency(subtotal) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="shippingLabel" colspan="3">' +
					'Shipping (' + this.getShippingLocation() + '):' +
				'</td>';
				var rate = this.getShippingRate();
				html +=
				'<td id="shippingValue">' + formatCurrency(rate) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="totalLabel" colspan="3">Total:</td>' +
				'<td id="totalValue">US&nbsp;' + formatCurrency(subtotal + rate) + '</td>' +
			'</tr>' +
		'</table>';
		
		document.write(html);
	}
}

function Cart_displayReadOnlyCheckOut()
{
	var selections = this.getSelections();
	if (productSet == null)
	{
		productSet = new ProductSet();
	}
		
    if (this.isEmpty())
	{
		document.location = "index.html";
		return;
	}
	else
	{
		var html = '';
		html +=
		'<table id="shoppingCart" border="0" cellspacing="0" cellpadding="0" width="500">' +
			'<tr>' +
				'<th id="quantity" class="string">Quantity</th>' +
				'<th id="description" class="string">Description</th>' +
				'<th id="each" class="numeric">Each</th>' + 
				'<th id="total" class="numeric">Total</th>' +
			'</tr>';
        var subtotal = 0.0;
		var price = 0.0;
	    for (var i = 0; i < selections.length; i++)
	    {
	        var product = productSet.getProduct(selections[i].getId());
			price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
	        html +=
			'<tr>' +
				'<td class="string">' +
					selections[i].getQuantity() +
				'</td>' +
				'<td class="string">' +
					product.getDescription() +
				'</td>' +
				'<td class="numeric">' + formatCurrency(price) + '</td>' + 
				'<td class="numeric">' + formatCurrency(price * selections[i].getQuantity()) + '</td>' +
			'</tr>';
            subtotal += price * selections[i].getQuantity();
        }
		
		html +=
			'<tr>' +
				'<td id="subtotalLabel" colspan="3">Subtotal:</td>'+
				'<td id="subtotalValue">' + formatCurrency(subtotal) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="shippingLabel" colspan="3">' +
					'Shipping (' + this.getShippingLocation() + '):' +
				'</td>';
				var rate = this.getShippingRate();
				html +=
				'<td id="shippingValue">' + formatCurrency(rate) + '</td>' +
			'</tr>' +
			'<tr>' +
				'<td id="editLink">';
					var paymentMethod = this.getPaymentMethod();
					if (paymentMethod == "PayPal" || paymentMethod == "creditCard")
					{
						html +=
						'<a href="checkOut_reviewOrder_payPalOrder_editable.html">edit</a>';
					}
					else
					{
						html +=
						'<a href="checkOut_reviewOrder_mailOrder_editable.html">edit</a>';
					}
				html +=
				'</td>' +
				'<td id="totalLabel" colspan="2">Total:</td>' +
				'<td id="totalValue">US&nbsp;' + formatCurrency(subtotal + rate) + '</td>' +
			'</tr>' +
		'</table>';
		
		document.write(html);
	}
}

function Cart_writePayPalForm()
{
	if (productSet == null)
	{
		productSet = new ProductSet();
	}

	var html =
	'<form action="' + getPayPalUrl() + '" method="post">' +
		'<input type="hidden" id="cmd" name="cmd" value="_cart">' +
		'<input type="hidden" id="upload" name="upload" value="1">' +
		'<input type="hidden" id="business" name="business" value="' + getCustomerServiceEmailAddress() + '">' +
		'<input type="hidden" id="handling_cart" name="handling_cart" value="' + this.getShippingRate() + '">' +
		'<input type="hidden" id="currency_code" name="currency_code" value="USD">' +
		'<input type="hidden" id="cpp_header_image" name="cpp_header_image" value="' + getBaseUrl() + '/images/payPalLogo.gif">' +
		'<input type="hidden" id="return" name="return" value="' + getBaseUrl() + '/shopping/checkOut_payPalOrderComplete.html">' +
		'<input type="hidden" id="cancel_return" name="cancel_return" value="' + getBaseUrl() + '/shopping/">';
	
	var selections = this.getSelections();
	if (selections != null)
	{
		for (var i = 0; i < selections.length; i++)
		{
			var product = productSet.getProduct(selections[i].getId());
			var price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
			html +=
			'<input' +
				' type="hidden"' +
				' name="item_name_' + (i + 1) + '"' +
				' value="' + product.getDescription() + '"' +
			'>' +
			'<input' +
				' type="hidden"' +
				' name="quantity_' + (i + 1) + '"' +
				' value="' + selections[i].getQuantity() + '"' +
			'>' +
			'<input' +
				' type="hidden"' +
				' name="amount_' + (i + 1) + '"' +
				' value="' + price + '"' +
			'>';
		}
	}
	
	html +=
	'</form>';
	
	document.write(html);
}

function Cart_writeMailOrderForm()
{
	if (productSet == null)
	{
		productSet = new ProductSet();
	}

	var html =
	'<form method="post" action="' + getFormMailAction() + '">' +
		'<input type="hidden" name="username" id="username" value="' + getCustomerServiceEmailAddress() + '">' +
		'<input type="hidden" name="realname" id="realname" value="Myles Pinkney Online Gallery">' +
		'<input type="hidden" name="subject" id="subject" value="Mail Order from Web Site - The Myles Pinkney Online Gallery">' +
		'<input type="hidden" name="sender" id="sender" value="' + getCustomerServiceEmailAddress() + '">' +
		'<input type="hidden" name="recipient" id="recipient" value="' + getCustomerServiceEmailAddress() + '">' +
		'<input type="hidden" name="redirect" id="redirect" value="' + getBaseUrl() + '/shopping/checkOut_printAndMailOrderForm.html">' +
		'<input type="hidden" name="shippingLocation" id="shippingLocation" value="' + this.getShippingLocation() + '">' +
		'<input type="hidden" name="shippingCharge" id="shippingCharge" value="' + this.getShippingRate() + '">';
	
	var selections = this.getSelections();	
	if (selections != null)
	{
		for (var i = 0; i < selections.length; i++)
		{
			var product = productSet.getProduct(selections[i].getId());
			var price = product.getDiscountPrice() > 0.0 ? product.getDiscountPrice() : product.getUnitPrice();
			html +=
			'<input' +
				' type="hidden"' +
				' name="itemDescription' + (i + 1) + '"' +
				' value="' + product.getDescription() + '"' +
			'>' +
			'<input' +
				' type="hidden"' +
				' name="itemQuantity' + (i + 1) + '"' +
				' value="' + selections[i].getQuantity() + '"' +
			'>' +
			'<input' +
				' type="hidden"' +
				' name="itemUnitPrice' + (i + 1) + '"' +
				' value="' + price + '"' +
			'>' +
			'<input' +
				' type="hidden"' +
				' name="itemTotal' + (i + 1) + '"' +
				' value="' + (selections[i].getQuantity() * price) + '"' +
			'>';
		}
	}
	
	html +=
	'</form>';
	
	document.write(html);
}

function Cart_updateFromPage()
{
	if (this.isEmpty())
	{
		return;
	}

	var selections = this.getSelections();
	var numSelections = 0;
    for (var i = 0; i < selections.length; i++)
    {
		var textfield = document.getElementById(CART_QUANTITY_KEY_PREFIX + selections[i].getId());
		var newQuantity = parseInt(textfield.value);
		if (isNaN(newQuantity))
		{
            selections[i].quantity = 1;
			numSelections++;
		}
		else
        {
            if (newQuantity == 0)
			{
                selections[i] = null;
			}
            else
			{
                selections[i].quantity = newQuantity;            
				numSelections++;
			}
        }
    }
	if (numSelections == 0)
	{
		selections = null;
	}
    this.setSelections(selections);
    
	this.persist();
	
    //
    // Go to Shopping Cart
    //
    //document.location = "../shopping/index.html";
}

/*-- End Cart ----------------------------------------------------------------------------------*/

/*-- Start CartSelection -----------------------------------------------------------------------*/

function CartSelection(id, quantity)
{
	this.setId = CartSelection_setId;
	this.getId = CartSelection_getId;
	this.setId(id);
	
	this.setQuantity = CartSelection_setQuantity;
	this.getQuantity = CartSelection_getQuantity;
	this.setQuantity(quantity);
	
	return this;
}

function CartSelection_setId(id)
{
	this.id = id;
}

function CartSelection_getId()
{
	return this.id;
}

function CartSelection_setQuantity(quantity)
{
	this.quantity = quantity;
}

function CartSelection_getQuantity()
{
	return this.quantity;
}

function Cart_refreshPage()
{		
    //
    // Go to Shopping Cart
    //
	//document.location = "../shopping/index.html";
	window.location.reload();
}

/*-- End CartSelection -------------------------------------------------------------------------*/

function quantityCardsChanged(list)
{
	var product = productSet.getProduct('christmas-time-cards-' + list.value);
	document.getElementById('priceCards').innerHTML = formatCurrency(product.getUnitPrice());
}

function addToCartFromField(id, quantityFieldId)
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	
	var obj = document.getElementById(quantityFieldId);
	var quantity = 1;
	if (isInteger(obj.value))
	{
		quantity = parseInt(obj.value);
		if (isNaN(quantity) || quantity <= 0)
		{
			quantity = 1;
		}
	}
	
	obj.value = "" + quantity;
	
	addToCart(id, quantity);
}

function addToCart(id, quantity)
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
    var selections = shoppingCart.getSelections();
    var newSelections = null;
    var alreadySelected = false;
	if (selections == null)
    {
	    newSelections = new Array(new CartSelection(id, quantity));
        shoppingCart.setSelections(newSelections);
    }
	else
    {
        // Ensure selection isn't already in cart
        for (var i = 0; i < selections.length && !alreadySelected; i++)
        {
            if (selections[i].getId() == id)
			{
			   selections[i].setQuantity(quantity);
 	           shoppingCart.setSelections(selections);
               alreadySelected = true;
			}
        }
              
        // Set up new array of selections
        if (alreadySelected == false)
        {
            newSelections = new Array(selections.length + 1);
            for (var i = 0; i < selections.length; i++)
			{
                newSelections[i] = selections[i];
			}
            newSelections[selections.length] = new CartSelection(id, quantity);
            shoppingCart.setSelections(newSelections);
        }
    }
    
	shoppingCart.persist();
	
	//shoppingCart.refreshPage();
	document.location = "../shopping/index.html";
}

function updateShoppingCart()
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
	shoppingCart.updateFromPage();
	
	shoppingCart.refreshPage();
}

function removeShoppingCartSelection(id)
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}

	shoppingCart.removeSelection(id);
}

function shippingLocationChanged(list)
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
	var location = list.options[list.selectedIndex].value;
	shoppingCart.setShippingLocation(location);
	
	shoppingCart.persist();
	
	shoppingCart.refreshPage();
}

function checkOutNext(currentPage)
{
	if (currentPage == "selectPaymentMethod")
	{
		if (shoppingCart == null)
		{
			shoppingCart = new Cart();
			shoppingCart.initialize();
		}
	    
		var paymentMethod = getSelectedRadioValue(document.forms[0].paymentMethod);
		shoppingCart.setPaymentMethod(paymentMethod);
		
		shoppingCart.persist();
		
		if (paymentMethod == "mailOrder")
		{
			document.location = "checkOut_reviewOrder_mailOrder.html";
		}
		else
		{
			document.location = "checkOut_reviewOrder_payPalOrder.html";
		}
	}
	else if (currentPage == "reviewOrder")
	{
		if (shoppingCart == null)
		{
			shoppingCart = new Cart();
			shoppingCart.initialize();
		}
	    
		var paymentMethod = shoppingCart.getPaymentMethod();
		if (paymentMethod == "PayPal" || paymentMethod == "creditCard")
		{
			document.forms[0].submit();
		}
		else
		{
			// Submit mail order form
			shoppingCart.saveMailOrder();
			//document.location = "checkOut_printAndMailOrderForm.html";
			document.forms[0].submit();
		}
	}
}

function checkOutBack(currentPage)
{
	if (currentPage == "selectPaymentMethod")
	{
		document.location = "index.html";
	}
	else if (currentPage == "reviewOrder")
	{
		document.location = "checkOut_selectPaymentMethod.html";
	}
	else if (currentPage == "printAndMailOrderForm")
	{
		document.location = "checkOut_reviewOrder_mailOrder.html";
	}
}

function writePayPalForm()
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
	shoppingCart.writePayPalForm();
}

function writeMailOrderForm()
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
	shoppingCart.writeMailOrderForm();
}

function updateCartFromPage()
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}
	    
	shoppingCart.updateFromPage();
}

function displayShippingRates()
{
	if (shoppingCart == null)
	{
		shoppingCart = new Cart();
		shoppingCart.initialize();
	}

	var html =
	'<table id="shippingRates" border="0" cellspacing="0" cellpadding="0">';
	
	var rates = shoppingCart.getShippingRates();
	for (var i = 0; i < rates.length; i++)
	{
		html +=
		'<tr>' +
			'<td class="location">' + rates[i].getLocation() + '</td>' +
			'<td class="amount">' + formatCurrency(rates[i].getRate()) + '</td>' +
		'</tr>';
	}
	
	html +=
	'</table>';
	
	document.write(html);
}

