// Custom shopping cart for concentric.org, v2.3.010
// Includes PHP functionality for cross domain cookies
// Logic file for the shopping cart.  An understanding of javascript is required 
// beyond this point. 

var intItemCost = 0; //Subtotal
var intShipping = 0; // Shipping Amount
var intTax = 0; // Tax amount
var intTotalCost = 0; // Order Total Cost
var blnTaxed = false;
var strPaypalOutput = "";

// Checks to be sure a string is a quantity.  Argument is a string, returns 
// only numeric.
function checkNumeric(strCheckString)
{
	var strFixedString = "";
	var strChar = "";

	for ( i = 0; i < strCheckString.length; i++ )
	{
	strChar = strCheckString.substring(i, i+1);
		if (strChar >= "0" && strChar <= "9")
		{
			strFixedString += strChar;
		}
	}

	if (strFixedString.length < 1)
		{
			strFixedString = "";
		}
	
	return(strFixedString);
}

// Formats input as #.## for output since JS uses large floats.  Argument is a  
// number, return is formatted
function moneyFormat(fltInput)
{
	var intFormated = Math.round(fltInput*100)/100;
	intFormated = intFormated.toFixed(2);
	return(intFormated);
}

// Checks that the customer has selected a tax option
function checkTax()
{
	if (document.getElementById("taxed").checked || document.getElementById("notaxed").checked)
	{
		var aryCurrentCart = new Array();
		aryCurrentCart = getCartArray(strCartName);
		intCartDuration = 1;
		setCookie(strCartName,aryCurrentCart);
		return true;
	}
	alert(strTaxPrompt);
	return false;
}

// Stores a cookie in the users browser. Arguments are name, value and
// expiration in days.  Sets cookie to root path and current domain.
function setCookie (strCookieName,aryCart)
{
	var strNewCart = "";
	var exDate = new Date();
	exDate.setDate(exDate.getDate()+intCartDuration);

	for (i=0; i<aryCart.length; i++)
	{
		aryCart[i] = aryCart[i].join("|");		
	}
	strNewCart = aryCart.join("^");

	document.cookie = strCookieName + "=" + escape(strNewCart) + 
                     ((intCartDuration == null) ? "" : "; expires=" + exDate.toGMTString()) +
                     "; path=/";
}

// Removes a cookie from user's browser.  Only argument is cookie name.
function deleteCookie (strCookieName)
{
	var exDate = new Date();
		exDate.setDate(exDate.getDate()-1);
		document.cookie = strCookieName + "=" + " " + "; expires=" + exDate.toGMTString() + "; path=/";
}

// Retrieves information store in the cookie.  Argument is the cookie name,
// returns the cookie value.
function getCookie(strCookieName)
{
	var intCookieStart = 0;
	var intCookieEnd = 0;
	
	if (document.cookie.length>0)
	{
		intCookieStart=document.cookie.indexOf(strCookieName + "=");
		if (intCookieStart!=-1)
		{
			intCookieStart=intCookieStart + strCookieName.length+1;
			intCookieEnd=document.cookie.indexOf(";",intCookieStart);
			if (intCookieEnd==-1) 
	    	{
				intCookieEnd=document.cookie.length;
		    }
		    if (intCookieStart == intCookieEnd)
		    {
		    	return null;
		    }
			return unescape(document.cookie.substring(intCookieStart,intCookieEnd));
		} 
	}
	return null;
}

// Places the cart into an array from the cookie.  Arguement is cart name, 
// which is cookie name.  Returns cart contents in an array.
function getCartArray(strCartName)
{
	var i=0
	var aryCurrentCart = new Array();
	var strCurrentCart = "";
	
	strCurrentCart = getCookie(strCartName);
	if (strCurrentCart != null)
	{
		aryCurrentCart = strCurrentCart.split("^");
	}

	for (i=0; i<aryCurrentCart.length; i++)
	{
		aryCurrentCart[i] = aryCurrentCart[i].split("|");
		aryCurrentCart[i][1] = parseFloat(aryCurrentCart[i][1]);
	}
	return aryCurrentCart;
}

// Finds item location in cart array, returns index of the item.  If not in 
// cart, returns -1.  Arguements are Item ID as a string and the cart array
function checkItemLocation (strItemID, aryCartContents, strLanguage, strType)
{
	var i=0;
	var intItemIndex = -1;
	for (i=0; i<aryCartContents.length; i++)
	{
		if (aryCartContents[i][0]==strItemID && aryCartContents[i][2]==strLanguage && aryCartContents[i][3]==strType)
		{
			intItemIndex = i;
		}
	}
	return intItemIndex;
}


// Adds item to cart, increases amount if already in cart.  Sends user to 
// cart after adding item with return button available.
function addToCart(intQuantityAdd, strItemID, strLanguage, strType)
{
	if (strItemID != "")
	{
		var intNumItemsOrdered = 0;
		var aryCartContents = new Array();
		var intItemIndex = -1;
		var intNewQuantity = parseFloat(intQuantityAdd);
		aryCartContents = getCartArray(strCartName);
		intNumItemsOrdered = aryCartContents.length;
		intItemIndex = checkItemLocation(strItemID,aryCartContents, strLanguage, strType);

		if (intNumItemsOrdered > 49)
		{
			alert("We're sorry, but you cannot have more than 50 items in your cart.");
			return;
		}
	
		if (intItemIndex > -1) // Cart exists, item in cart, increment quantity
		{
			aryCartContents[intItemIndex][1] += intNewQuantity;
		}else{ // No cart, or item not in cart, add new item
			var aryNewItem = new Array(strItemID, intNewQuantity, strLanguage,strType);
			aryCartContents.push(aryNewItem);
		}

	// Write Cart to Cookie
		deleteCookie(strCartName);
		setCookie(strCartName, aryCartContents);
	}
}

// Remove item from cart.  Arguements are form elements, returns Cart Page
function removeFromCart(intItemID)
{
	if (confirm(strRemove)) 
	{
		var aryCartContents = new Array();
		aryCartContents = getCartArray(strCartName);
		aryCartContents.splice(intItemID, 1);
		deleteCookie(strCartName);
		setCookie(strCartName, aryCartContents);
		location.href=location.href;
	}
}

// Changes the quantity in the cart
function changeQuantity(intItemID, intNewQuantity)
{
	var aryCartContents = new Array();
	aryCartContents = getCartArray(strCartName);
	intNewQuantity = parseFloat(intNewQuantity);
	if (isNaN(intNewQuantity))
	{
		alert(strErrorQuantity);
		document.getElementById("txtQuan"+intItemID).value = aryCartContents[intItemID][1];
	}else{
		aryCartContents[intItemID][1] = intNewQuantity;
		deleteCookie(strCartName);
		setCookie(strCartName,aryCartContents,intCartDuration);
		location.href = location.href;
	}
}

// Manages all cart calculations and outputs cart page
function manageCart()
{
	var i = 0;
	var intNumItemsPriceBreak = 0; // Items that trigger a break, dvds
	var intNumItemsShipBreak = 0; // Items that trigger the shipping break levels
	var intNumSpecialShip = 0; // Items that have special added shipping
	var strShipBreakLevel = "";
	var strPriceBreakLevel = "";
	var aryCartContents = new Array();
	var strPageOutput = ""; // Output for page display

	
	aryCartContents = getCartArray(strCartName);

	if ( aryCartContents.length == 0 )
	{
		strPageOutput += "<tr><td colspan=\"5\" class=\"dgcEntry\"><br><strong>Your cart is empty</strong><br /><br /></td></tr>";
	}else{
		strPaypalOutput += 	'<form class="dgcHidden" action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="return checkTax()">'+
							'<input type="hidden" name="cmd" value="_cart">'+
							'<input type="hidden" name="upload" value="1">'+
							'<input type="hidden" name="business" value="'+strEbayID+'">';
		// Basic Break Calc
		for (i=0; i<aryCartContents.length; i++)
		{
			var strTempID = "";
			var intTempQuan = 0;
			strTempID = aryCartContents[i][0];
			intTempQuan = aryCartContents[i][1];
			switch (aryCartContents[i][3])
			{
				case "DVD":
					objProductList[strTempID].PriceBreak = "True";
					break;
				case "CD":
					objProductList[strTempID].PriceBreak = "True";
					break;
				case "VHS":
					objProductList[strTempID].PriceBreak = "False";
					break;
			}
			if (objProductList[strTempID].PriceBreak == "True")
			{
				intNumItemsPriceBreak+= intTempQuan;
			}
			if (objProductList[strTempID].ShipBreak == "True")
			{
				intNumItemsShipBreak+= intTempQuan;
			} 
			if (objProductList[strTempID].ShipBreak == "Special")
			{
				intNumItemsShipBreak+= intTempQuan;
				intNumSpecialShip+= intTempQuan;
			}
		}

		switch (true)
		{
			case intNumItemsPriceBreak >= intBreak2:
				strPriceBreakLevel = "three";
				break;
			case intNumItemsPriceBreak == intSpecialBreak:
				strPriceBreakLevel = "special";
				break;
			case intNumItemsPriceBreak >= intBreak1:
				strPriceBreakLevel = "two";
				break;
			default:
				strPriceBreakLevel = "one";
				break;
		}
		switch (true)
		{
			case intNumItemsShipBreak >= intBreak2:
				strShipBreakLevel = "three";
				break;
			case intNumItemsShipBreak == intSpecialBreak:
				strShipBreakLevel = "special";
				break;
			case intNumItemsShipBreak >= intBreak1:
				strShipBreakLevel = "two";
				break;
			default:
				strShipBreakLevel = "one";
				break;
		}
		// Price Calc and table line additions for each item
		var intTempCostBreak=0;
		var intTempCostNoBreak=0;
		var intPaypalShippingNum=0;
		for (i=0; i<aryCartContents.length; i++)
		{
			var strTempID = "";
			var intTempQuan = 0;
			var strTempLang = "";
			var strTempType = "";
			var strTempLangType = "";
			
			strTempID = aryCartContents[i][0];
			intTempQuan = aryCartContents[i][1];
			strTempType =((aryCartContents[i][3]!=undefined)?" "+aryCartContents[i][3]:""); 
			switch (aryCartContents[i][3])
			{
				case "DVD":
					objProductList[strTempID].PriceBreak = "True";
					break;
				case "CD":
					objProductList[strTempID].PriceBreak = "True";
					break;
				case "VHS":
					objProductList[strTempID].PriceBreak = "False";
					break;
			}
			switch (aryCartContents[i][2])
			{
				case "ENG":
					strTempLang = "English";
					break;
				case "SPA":
					strTempLang = "Spanish";
					break;
				case "AMH":
					strTempLang = "Amharic";
					break;
			}
			if (strTempLang != "")
			{
				strTempLangType += ' ('+strTempLang+' '+strTempType+')';
			}
			
			strPageOutput += 	"<tr>"+
								"<td class=\"dgcEntry\">"+objProductList[strTempID].ProductName+strTempLangType+"</td>"+ //Description
								"<td class=\"dgcEntry\"><input type=\"text\" name=\"Q\" size=\"2\" id=\"txtQuan"+i+"\" value=\"" + intTempQuan + "\" onChange=\"changeQuantity("+i+", this.value);\" onkeyup=\"this.value=checkNumeric(this.value)\" maxlength=\"3\"></td>"; //Quantity Box
			strPaypalOutput +=	'<input type="hidden" name="item_name_'+(i+1)+'" value="'+objProductList[strTempID].ProductName+strTempLangType+'">'+
								'<input type="hidden" name="quantity_'+(i+1)+'"value="'+intTempQuan+'">';
			intPaypalShippingNum = i+2;

			if (objProductList[strTempID].PriceBreak=="True")//Price Break Items
			{
				intTempCostBreak += intTempQuan*objProductList[strTempID].ProductPrice[strPriceBreakLevel];
				if (strPriceBreakLevel == "special")//Special price number
				{
					strPageOutput+=	"<td class=\"dgcEntry\">-</td>"+ //Price each
									"<td class=\"dgcEntry\">Special</td>"; //Extended Price
					strPaypalOutput+=	'<input type="hidden" name="amount_'+(i+1)+'" value="0.00">';
					intTempCostBreak = 100;
				}else{//Normal price break items
					strPageOutput+=	"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(objProductList[strTempID].ProductPrice[strPriceBreakLevel])+"</td>"+ //Price each
									"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(intTempQuan*objProductList[strTempID].ProductPrice[strPriceBreakLevel])+"</td>"; //Extended Price
					strPaypalOutput+= '<input type="hidden" name="amount_'+(i+1)+'" value="'+moneyFormat(objProductList[strTempID].ProductPrice[strPriceBreakLevel])+'">';
				}
			}else if (aryCartContents[i][3] == "VHS"){// For VHS option
				intTempCostBreak += intTempQuan*objProductList[strTempID].ProductPrice.vhs;
					strPageOutput+=	"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(objProductList[strTempID].ProductPrice.vhs)+"</td>"+ //Price each
									"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(intTempQuan*objProductList[strTempID].ProductPrice.vhs)+"</td>"; //Extended Price
					strPaypalOutput+= '<input type="hidden" name="amount_'+(i+1)+'" value="'+moneyFormat(objProductList[strTempID].ProductPrice.vhs)+'">';
		}else{//For Everything else, no price break
				intTempCostNoBreak += intTempQuan*objProductList[strTempID].ProductPrice[strPriceBreakLevel];
				strPageOutput+=	"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(objProductList[strTempID].ProductPrice[strPriceBreakLevel])+"</td>"+ //Price each
								"<td class=\"dgcEntry\">"+strMonetarySymbol+moneyFormat(intTempQuan*objProductList[strTempID].ProductPrice[strPriceBreakLevel])+"</td>"; //Extended Price
				strPaypalOutput+=	'<input type="hidden" name="amount_'+(i+1)+'" value="'+moneyFormat(objProductList[strTempID].ProductPrice[strPriceBreakLevel])+'">';
			}
			strPageOutput+=	'<td class="dgcRemove dgcEntry"><img onclick="removeFromCart('+i+')" src="./images/dgcRemove.gif" alt="Remove" /></td></tr>'; //Remove Button
		}
		if (strPriceBreakLevel == "special")
		{
			strPaypalOutput+=	'<input type="hidden" name="item_name_'+(i+1)+'" value="Special Price, 12 Items">'+
								'<input type="hidden" name="amount_'+(i+1)+'" value="100.00">';
			intPaypalShippingNum+= 1;
		}
		intItemCost = intTempCostBreak+intTempCostNoBreak; //Finally add costs
		// Shipping Calc	
		intShipping = objShipping[strShipBreakLevel];
		if (intNumItemsPriceBreak == 0)
		{ //If no break items ordered
			for (i=1; i<intNumSpecialShip; i++)
			{
				intShipping+= intAdditionalShipping;
			}
		}else { //If break items ordered
			for (i=0; i<intNumSpecialShip; i++)
			{
				intShipping+= intAdditionalShipping;
			}
		}
		strPaypalOutput+=	'<input type="hidden" name="amount_'+intPaypalShippingNum+'" value="'+moneyFormat(intShipping)+'">'+
							'<input type="hidden" name="item_name_'+intPaypalShippingNum+'" value="Shipping and Handling">';
		// Tax Calc, includes shipping
		intTax = intTaxRate*(intItemCost+intShipping);
		// Bottom of cart

	}
	document.write(strPageOutput);
	document.close();
}

// Updates the bottom portion of the cart
function updateTotal()
{
	blnTaxed = document.getElementById("taxed").checked;
	if (blnTaxed)
	{
		intTotalCost = moneyFormat(intItemCost+intTax+intShipping);
		strPaypalOutput+=	'<input type="hidden" name="tax_cart" value="'+moneyFormat(intTax)+'">';
	}else{
		intTotalCost = moneyFormat(intItemCost+intShipping);
	}
	document.getElementById("subtotal").innerHTML = strMonetarySymbol+moneyFormat(intItemCost);
	document.getElementById("shipping").innerHTML = strMonetarySymbol+moneyFormat(intShipping);
	document.getElementById("taxText").innerHTML = strMonetarySymbol+moneyFormat(intTax);
	document.getElementById("taxed").value = intTax;
	document.getElementById("total").innerHTML = strMonetarySymbol+moneyFormat(intTotalCost);
	document.getElementById("dgcCheckout").innerHTML = strPaypalOutput+	'<input type="hidden" name="cancel_return" value="http://www.concentric.org/dgcCart/dgcManage.php">'+
																		'<input type="hidden" name="cbt" value="Complete Transaction">'+
																		'<input type="hidden" name="no_shipping" value="2">'+
																		'<input type="hidden" name="return" value="http://www.concentric.org/dgcCart/complete.html">'+
																		'<input type="hidden" name="shopping_url" value="http://www.concentric.org/">'+
																		'<input type="hidden" name="rm" value="1">'+
																		'<input type="hidden" name="page_style" value="dgcCart">'+
																		'<input type="image" name="submit" src="./images/dgcCheckout.gif" alt="Checkout"></form>';
}