////////////////////////////////////////////////////////////////////////////
//  PROGRAM NAME:   cart.js JavaScript Shopping Cart
//  AUTHOR:         John Curtis, Alion Science and Technology
//  DATE CREATED:   Feb 5, 2004 jgc
//  PURPOSE:        This script maintains user shopping cart data for the 
//                  e-commerce portion of the web site
////////////////////////////////////////////////////////////////////////////
// The cart data consistes of five parallel arrays 
var ProductName = new Array();
var ProductCode = new Array();
var ProductdCost = new Array();
var ProductfCost = new Array();
var ProductQty = new Array();
var ProductType = new Array();
var ProductShip = new Array();
// entry point storage for reloading page
var docLocation
// order data
var strOrder

// The SetCookie function saves the passed named cookie & data
function SetCookie(Name,Data){
	// if cookie is to be persistant it must have an experation date
	var modData;
	var expDate = new Date();
	var nextDay = expDate.getTime() + (24 * 60 * 60 * 1000);
	expDate.setTime(nextDay);
	modData=Data.join("|");
	// if session cookie is required comment out the date
	document.cookie = Name + '=' + modData + ';path=/;';// + "expires=" + expDate.toGMTString();
}

// The GetCookie function retrieves cookie data based on passed name
function GetCookie(Name){
	var nameLen = Name.length;
	var cookieData = document.cookie;
	var cookieLen = cookieData.length;
	var Index = 0;
	var End;
		//parse out the string based on passed name followed by "=" sign
	while (Index < cookieLen){
		var Start = Index + nameLen;
		if(cookieData.substring(Index,Start) == Name){
			End = (cookieData.indexOf(";",Start));
			if(End ==-1)
				End = cookieData.length;
			//get data only and return to caller
			return unescape(cookieData.substring(Start+1,End));
		}
		Index++;
	}	
	return "";
}

// The ParseArray function separates the cookie data into a 0 based array
function ParseArray(Data){
	// initialize startup parameters
	var i = -1,CurrentVar = 0,LastEntry = 0;
	var PBuffer = new Array();
	// give data string a terminator
	Data = Data + ';';
	// loop through the passed data 'til the first ";"
	do	{
		// bump index pointer
		i++;
		// check for separator or end
		if(Data.charAt(i) == '|' || Data.charAt(i) == ';')	{
			// when we hit a "|" or ";" the temp array at the current index
			// is populated with the data found between the last find and the
			// separating character
			PBuffer[CurrentVar] = Data.substring(LastEntry,i);
			// bump the temp array index
			CurrentVar++;
			// set the last data pointer past the separator character
			LastEntry = i + 1;
		}
	// quit loop when we hit a terminating character
	}while(Data.charAt(i) != ';')
	// return data to caller
	return(PBuffer);
}

// The Additem function returns
function AddItem(Name,Code,dPrice,fPrice,Type,Ship){
	var i = 0,Flag = false;
	// get the return location for reload
	docLocation=document.location;
	// add the passed items to their appropriate arrays
	do{
		// if this is the first one save at 0 index
		if(ProductName.length == 0){
		
			ProductName[0] = Name;
			ProductCode[0] = Code;
			ProductdCost[0] = dPrice;
			ProductfCost[0] = fPrice;
			// initial quanty is 1
			ProductQty[0] = 1;
			// if product is web downloadable
			ProductType[0] = Type;
			// if product has extra shipping
			ProductShip[0] = Ship;
			// set exit flag
			Flag = true;
		}
		else{
			// if we already have this item then simply bump the quantity
			if(ProductName[i] == Name){
				ProductQty[i] = parseInt(ProductQty[i]) + 1;
				// and exit
				Flag = true;
			}
			else
				i++;
			// if this item is not yet in cart place at the end of the array
			if(i == ProductName.length){
				ProductName[i] = Name;
				ProductCode[i] = Code;
				ProductdCost[i] = dPrice;	
				ProductfCost[i] = fPrice;
				// with an initital quantity of 1
				ProductQty[i] = 1;			
				// if product is web downloadable
				ProductType[i] = Type;
				// if product has extra shipping
				ProductShip[i] = Ship;
				// and exit
				Flag = true;
			}
		}
	}while(!Flag);
	// save as cookies
	SetCookie("SRCcartName",ProductName);
	SetCookie("SRCcartCode",ProductCode);	
	SetCookie("SRCcartdCost",ProductdCost);	
	SetCookie("SRCcartfCost",ProductfCost);
	SetCookie("SRCcartType",ProductType);
	SetCookie("SRCcartShip",ProductShip);
	SetCookie("SRCcartQty",ProductQty);
}

// The ShowHeaderCart function places a small version of the cart
// on the calling page
function ShowHeaderCart(checkOut,showCart){
	var i;
	var pname;
	var strOrder;
	var subtotal=0;

	var hostname = "https://ammtiac.alionscience.com";
	var loc = document.location.hostname;
	if(loc.indexOf("rome-boxenford")>-1 || loc.indexOf("172.20.30.45")>-1){
		hostname = "http://rome-boxenford.alionscience.com:81";
	}
	if(loc.indexOf("rome-iac" || loc.indexOf("172.20.30.2")>-1)>-1){
		hostname = "http://rome-iac.alionscience.com:82";
	}
	checkOut = hostname + checkOut;
	// spool through cart array if we have stuff
	document.write("<form name='checkoutform' method='post' action='" + checkOut + "'>");
	if(ProductName.length>1){
		for(i = 1;i < ProductName.length;i++){
			if (ProductName[i] != ""){
			// keep track of subtotal
				subtotal=subtotal+(ProductQty[i] * ProductdCost[i]);
			}				
		}
		
		i=ProductName.length-1;		
		// proper grammer
		document.write("&nbsp;<a href='" + showCart + "'><font color='blue'>Cart");
		if(i==1)
			document.write("&nbsp;(" + i + " item)</font></a>");
		else
			document.write("&nbsp;(" + i + " items)</font></a>");	
		//document.write("");	 Subtotal:&nbsp;" + dollarize(subtotal) + ")
		document.write("<a href='" + showCart + "'><img src='/images/bfullcart.gif' alt='' border='0'></a>");			
	}
	// if not indicate no items
	else{
		document.write("&nbsp;<a href='" + showCart + "'><font color='blue'>Cart&nbsp;(0 items)</font></a><img src='/images/bemptycart.gif' alt='' border='0'>");
	}	

	//provide link to checkout
	
	if(i>0){	
		strOrder="";
		for(cnt=1;cnt<ProductName.length;cnt++){
			strOrder = strOrder + ProductCode[cnt] + ";" + ProductName[cnt] + ";" + ProductType[cnt] + ";" + 
							   ProductdCost[cnt] + ";" + ProductfCost[cnt] + ";" + ProductShip[cnt] + ";" + ProductQty[cnt] + "|";
		}
		document.write("<input type='hidden' name='prodorder' value='" + strOrder + "'>");		
	}			
	document.write("<a href='javascript: submitform()' title='Submit Form'><font color='blue'>Checkout</font></a>");	
	document.write("</form>");											
}

function submitform()
{
	if(ProductName.length>1){
		document.checkoutform.submit();	
	}
	else{
		showEmptyMsg();
	}	
  
}

function showProperties(obj,objname){
	var result ="";
	for (var i in obj){
		result += objname + "." + i + " = " + obj[i] +"<br>";
	}
	return result;
}
function ChangeItem(i,qty){
	if(ProductName.length != 0){
		if(qty>0){
			ProductQty[i] = qty;
			SetCookie("SRCcartQty",ProductQty);
		}
		else
			RemoveItem(i);
	}
}

function InitCart()
{
	//alert("InitCart");
	var Buffer;
	Buffer = GetCookie("SRCcartName");
	ProductName = ParseArray(Buffer);
	Buffer = GetCookie("SRCcartCode");
	ProductCode = ParseArray(Buffer);
	Buffer = GetCookie("SRCcartdCost");
	ProductdCost = ParseArray(Buffer);
	Buffer = GetCookie("SRCcartfCost");
	ProductfCost = ParseArray(Buffer);
	Buffer = GetCookie("SRCcartType");
	ProductType = ParseArray(Buffer);
	Buffer = GetCookie("SRCcartShip");
	ProductShip = ParseArray(Buffer);	
	Buffer = GetCookie("SRCcartQty");
	ProductQty = ParseArray(Buffer);
	//alert(ProductName.length);
}

function CheckCart(Code,showCart){
	var i;
	if(ProductName.length > 0){
		for(i = 0;i < ProductName.length;i++){
			//alert(ProductCode[i]);
			//alert(Code);
			if(ProductCode[i]==Code){
				document.write("<a href='" + showCart + "' target='_parent' class='linkmore'><font face='Verdana' size='1' color='blue'><b>This item is in your cart&nbsp;</font></b><img src='/images/bfullcart.gif' border='0' alt=''></a>");
			}
		}
	}
}

function CheckCartDetail(Name,Code,dCost,fCost,Webdl,Xship,showCart){
	var i;
	var ret;

	ret = "		<form name=\"" + Code + "\" method=\"post\" style=\"text-align:center;\" onsubmit=\"JavaScript: AddItem('" + Name + "','" + Code + "','" + dCost + "','" + fCost + "','" + Webdl + "','" + Xship + "');\">\n";
	ret = ret + "		<input type=\"image\" src=\"/images/placeincart.gif\" border=\"0\"></a></form>\n";	
	if(ProductName.length > 0){
		for(i = 0;i < ProductName.length;i++){
			if(ProductCode[i]==Code){
				ret = "<a href=\"" + showCart + "\" target=\"_parent\"><img src=\"/images/alreadyincart.gif\" border=\"0\"></a>";
			}
		}
	}
	document.write(ret);
}

function RemoveCart()
{
	var i;
	for(i = 0;i < ProductName.length;i++)	{
		ProductName[i] = "";
		ProductCode[i] = "";
		ProductdCost[i] = 0;
		ProductfCost[i] = 0;
		ProductType[i] = "";
		ProductShip[i] = "";
		ProductQty[i] = 0;
	}
	document.cookie = "SRCcartName=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";
	document.cookie = "SRCcartCode=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";
	document.cookie = "SRCcartdCost=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";
	document.cookie = "SRCcartfCost=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";
	document.cookie = "SRCcartType=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";	
	document.cookie = "SRCcartShip=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";		
	document.cookie = "SRCcartQty=;path=/;expires=Monday,04-Apr-1910 05:00:00 GMT";	
}

function RemoveItem(x){
	var i;
	var ii=0;
	var tempName = new Array();
	var tempCode = new Array();	
	var tempdCost = new Array();	
	var tempfCost = new Array();
	var tempType = new Array();
	var tempShip = new Array();
	var tempQty = new Array();	
	
	if(ProductName.length>2){
		for(i = 0;i < ProductName.length;i++){
			if(i!=x){
				tempName[ii]= ProductName[i];
				tempCode[ii] = ProductCode[i];
				tempdCost[ii] = ProductdCost[i];
				tempfCost[ii] = ProductfCost[i];
				tempType[ii] = ProductType[i];
				tempShip[ii] = ProductShip[i];
				tempQty[ii] = ProductQty[i];
				ii++;
			}
		}

		ProductName=tempName;
		ProductCode=tempCode;
		ProductdCost=tempdCost;
		ProductfCost=tempfCost;
		ProductType=tempType;
		ProductShip=tempShip;
		ProductQty=tempQty;

		SetCookie("SRCcartName",ProductName);
		SetCookie("SRCcartCode",ProductCode);	
		SetCookie("SRCcartdCost",ProductdCost);	
		SetCookie("SRCcartfCost",ProductfCost);
		SetCookie("SRCcartType",ProductType);
		SetCookie("SRCcartShip",ProductShip);
		SetCookie("SRCcartQty",ProductQty);
	}
	else
		RemoveCart();
}

function ShowCurrentCart(checkOut){
	var i;
	var cnt;
	var got_one=0;
	var got_spc=0;
	var subtotal=0;
	var ptotal=0;
	var fcode="";
	var prodlink;
	var regexp=/-/g;
	
	var shippage = "/ammt/jsp/order/shippingdetails.jsp";
	var hostname = "https://ammtiac.alionscience.com";
	var loc = document.location.hostname;
	if(loc.indexOf("rome-boxenford")>-1 || loc.indexOf("172.20.30.45")>-1){
		hostname = "http://rome-boxenford.alionscience.com:81";
	}
	if(loc.indexOf("rome-iac" || loc.indexOf("172.20.30.2")>-1)>-1){
		hostname = "http://rome-iac.alionscience.com:82";
	}
	checkOut = hostname + checkOut;

	if(ProductName.length>1){
		document.write("<tr>");
		document.write("<td align='center' bgcolor='#000'>");
		document.write("<table cellspacing='1' cellpadding='3' border='0' width='100%'>");
		document.write("<tr>");
		document.write("<td class='form4'>Item</td>");
		document.write("<td class='form4'>Product Code</td>");
		document.write("<td class='form4'>Quantity<sup>1</sup></td>");
		document.write("<td class='form4'>Cost<sup>2</sup></td>");
		document.write("<td class='form4'>&nbsp;</td>");
		document.write("</tr>");
		for(i = 1;i <ProductName.length;i++){
			if(ProductName[i] != ""){
				document.write("<tr>");
				document.write("<td class='normal'>");
				prodlink="<a href='products.do?action=detail&code=" + ProductCode[i] + "'>" + ProductName[i]
				if(ProductType[i]== "X"){
					prodlink=prodlink + "*";
					got_one++;
				}
				if(ProductShip[i]=="X"){
					prodlink=prodlink + "**";
					got_spc++;
				}
				prodlink=prodlink + "</a>";
				document.write(prodlink);
				document.write("</td>");
				document.write("<td class='normal'>");
				document.write(ProductCode[i]);
				fcode=ProductCode[i].replace(regexp,"x");
				document.write("</td>");
				document.write("<td bgcolor='#FFFFFF'>");
				document.write("<form name='" + fcode + "' method='GET' style='margin:0' onsubmit='JavaScript: ChangeItem(" + i + ",document." + fcode + ".qty" + i + ".value);'>");																								
				document.write("<input type='text' name='qty" + i + "' value='" + ProductQty[i] + "' size='1' maxlength='2'>");
				document.write("<input type='image' src='images/updateitem.gif'>");	
				document.write("<input type='hidden' name='action' value='cart'>");					
				document.write("</form>");		
				document.write("</td>");	
				document.write("<td class='rightbottom'>");
				ptotal=ProductQty[i] * ProductdCost[i];
				document.write(dollarize(ptotal));
				document.write("</td>");
				document.write("<td bgcolor='#FFFFFF'>");
				document.write("<form name='" + fcode + "Remove' method='GET' style='margin:0' onsubmit='JavaScript: RemoveItem(" + i + ");'>");				
				document.write("<input type='hidden' name='action' value='cart'>");
				document.write("<input type='image' src='images/deleteitem.gif'>");
				document.write("</form>");
				document.write("</td>");
				document.write("</TR>");		
				subtotal=subtotal+(ProductQty[i] * ProductdCost[i]);				
			}
		}
		document.write("<tr>");
		document.write("<td colspan='3' bgcolor='#FFFFFF'>");
		document.write("<table cellspacing='0' cellpadding='0' border='0' width='100%'>");
		document.write("	<tr>");
		document.write("		<td class='rightbottom'>");
		document.write("<b>Subtotal<sup>3</sup>:</b></td>");
		document.write("	</tr>");
		document.write("</table>");
		document.write("</td>");
		document.write("<td class='rightbottom'>" + dollarize(subtotal) + "</td>");
		document.write("<td class='rightbottom'>");
		document.write("<form name='removecart' method='post' onsubmit='JavaScript: RemoveCart();'>");											
		document.write("<input type='image' src='images/deleteall.gif'>");
		document.write("</form></td>");
		document.write("</tr>");	
		document.write("<tr>");
		document.write("<td class='normalsmall' colspan='5'><p>Notes:<br>");
		document.write("<sup>1</sup>To change the quantity of an item, change the quantity in the &quot;Quantity&quot; box, then click &quot;Update&quot;.<br>");		
		document.write("<sup>2</sup>Product cost shown is for US customers.<br>");									
		document.write("<sup>3</sup>Subtotal does not include <a href=\"JavaScript:popUp('" + shippage + "')\">shipping and handling</a> charges.<br>");
		document.write("</p></td>");		
		document.write("</tr>");
		document.write("</table>");
		document.write("</td>");
		document.write("</tr>");	
		if(got_one>0)
			document.write("<tr><td><table><tr><td width='100'></td><td class='centeredsmall'>* Indicates the product is a downloadable product.</td></tr></table></td></tr>");						
		if(got_spc>0)
			document.write("<tr><td><table><tr><td width='100'></td><td class='centeredsmall'>** Indicates the product requires additional shipping charges.  Click <a href=\"javascript:popUp('shippingdetails.jsp')\"><b>Here</b></a> for details.</td></tr></table></td></tr>");						
		document.write("<tr><td><table width='90%'>");
		document.write("<tr>");
		document.write("<td align='left' width='50%'><br>");
		document.write("<form name='resume' method='post' action='products.do?action=retain'>");
		document.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='image' src='images/resume.gif'>");
		document.write("</form>");
		document.write("</td>");		
		document.write("<td align='right' width='50%'><br>");
		document.write("<form name='checkout' method='post' action='" + checkOut + "'>");															
		document.write("<input type='image' src='images/cartout.gif'>");
		strOrder="";
		for(cnt=1;cnt<ProductName.length;cnt++){
			strOrder = strOrder + ProductCode[cnt] + ";" + ProductName[cnt] + ";" + ProductType[cnt] + ";" + 
							   ProductdCost[cnt] + ";" + ProductfCost[cnt] + ";" + ProductShip[cnt] + ";" + ProductQty[cnt] + "|";
		}
		document.write("<input type='hidden' name='prodorder' value='" + strOrder + "'>");		
		document.write("</form>");				
		document.write("</td>");
		document.write("</tr>");
		document.write("</table>");
		document.write("</td></tr>");									
	}
	else{
		document.write("<tr><td class='center'><br><br><h2>You have no items in your cart</h2><br><br>");
		document.write("<p align='center'><a href='products.do'><img border='0' src='images/resumeshopping.gif'></a></p><br><br></td></tr>");
	}
}

function Format(expr, decplaces){
	var str="" + Math.round(eval(expr)*Math.pow(10,decplaces));
	while ( str.length <= decplaces){
		str="0"+str;
	}
	var decpoint=str.length-decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function dollarize(expr){
	return "$" + Format(expr,2);
}

function showEmptyMsg(){
	alert("You have no items in your cart");
}