// Copyright (c) 2003, Nathan A. Sweet. All rights reserved. Contact: misc@n4te.com
// This file may not be modified or distributed in any form without written permission.

function addItem ( item, option, quantity, upgrade ) {
	if ( !option ) option = "";
	if ( !quantity ) quantity = 1;
	if ( !upgrade ) upgrade = 0;
	set( "gogItems", get("gogItems") + "~" + item + "|" + option + "|" + quantity + "|" + upgrade );
	document.location.href = "/cart.php";
}
function removeItem ( removeIndex ) {
	if ( !confirm("Are you sure you want to remove this item from your cart?") ) return;
	rebuild( "gogItems", removeIndex );
	update();
}

function addCoupon () {
	if (!document.couponForm.couponCode.value) return;
	set( "gogCoupons", get("gogCoupons") + "~" + document.couponForm.couponCode.value );
	document.location.href = "/cart.php";
}
function removeCoupon ( removeIndex ) {
	if ( !confirm("Are you sure you want to remove this coupon item from your cart?") ) return;
	rebuild( "gogCoupons", removeIndex );
	update();
}

function rebuild ( cookieName, removeIndex ) {
	var cookie = get( cookieName ).substring( 1 );
	if ( !cookie ) return;
	var oldCookieEntries = cookie.split( "~" );
	if ( removeIndex < 0 ) removeIndex = oldCookieEntries.length + removeIndex;
	var newCookie = "";
	for ( var i=0; i < oldCookieEntries.length; i++ ) {
		if ( i == removeIndex ) continue;
		switch ( cookieName ) {
		case "gogItems":
			var entry = oldCookieEntries[ i ].split( "|" );
			newCookie += "~" + entry[0] + "|" + entry[1] + "|" + document.cartForm[ "quantity" + i ].value + "|" + entry[3];
			break;
		case "gogCoupons":
			newCookie += "~" + oldCookieEntries[ i ];
			break;
		}
	}
	set( cookieName, newCookie );
}

function update () {
	rebuild( "gogItems" );
	rebuild( "gogCoupons" );
	document.location.href = "/cart.php";
}

function checkout () {
	var url = document.location.href;
	url = url.substring(url.indexOf(":"), url.lastIndexOf("/"));
	var protocol = (url.indexOf("://localhost") == 0) ? "http" : "https";
	document.location.href = protocol + url + "/checkoutPayment.php";
}
