
/*
	Global variable section
*/
var CookieTest=-1;
var BrowserTest=-1;
var AcceptsCookies=false;
var GoodBrowser=false;
var ProdDelim='^';
var CookieName='cart';
var CarValCookie='ccv';
var PopUpCookie='cv';
var CurrentCartValue; //keep tabs on cart amount
var MAX_CS_LEN = 2015; //max length allowed in query string
var UVCR;
//var qs=getQS();

//I need to know whether they are using the
//Visual Cart Representation.
if(document.usercart==null){
	UVCR = false;
}
else{
	UVCR = true;
}

function LARItem(ProdID,action){
	var numFrms=document.forms.length
	var retFrm,Found=false;
	for(var i=0;i<=numFrms;i++){ //cycle through all forms
		if(Found!=true){ //if I have already found the form exit
			var frm=document.forms[i] //assign a specific form
			if(frm!=null){
				for(var j=0;j<=frm.length;j++){ //cycle through the elements
					var e=frm.elements[j] //assign a specific element
					if(e!=null){ //make sure it has properties
						var n=e.name.toLowerCase(); //grab the name
						if(n=='fproductid'){ //test for needed field
							if(e.value==ProdID){ //if this is it ...
								retFrm=frm; // ... grab a reference to that object
								Found=true; //notify of foundness
								break; //quit this loop
							} 
						} 
					} //end null check
				} //end frm element loop
			} //end frm null check
		} //end found check
	} //end forms loop
	//call workhorse to take over with frm object and action call
	if(Found==true) ARItem(retFrm,action); 
	else{
		var msg='___________________________________\n\n';
		msg+='An error has occured, please contact\nthe site user with the following error\n';
		msg+='___________________________________\n\n';
		msg+='Product ID:'+ProdID+' not found, check the\nLARItem function make sure it is passing\na valid product id.';
		alert(msg);
	}
} 

/*
	Function: ARItem
	Purpose: To add and remove items selected by user into or out of the cookie
	Args: 2, frm (Form object), Action (Add, or Remove)
	Usage: To add an item you simply pass the form object, and the string 'add'. 
			Follow the same steps to remove an item from the basket, except 
			the action variable is 'remove'
*/
function ARItem(frm,action){
	if(BrowserTest==-1) GoodBrowser=TestBrowser();
	if(CookieTest==-1) AcceptsCookies=TestCookie(); //test to see if they accept cookies
	if(!AcceptsCookies) return; //if they do not, then exit	

	var ExistingCookie = '';
	var CarValCook = '';
	var cs='';
	var cartvalue=0;	
	var addItem;
	var frmAdds='';
	var ItemToRemove;
	
	//determine action of function, add or remove
	action=action.toLowerCase();
	if(action!='add')
		addItem=false;
	else 
		addItem=true;	
	 	
	//now I need to test to see if any other items exist
	ExistingCookie = getCookie(CookieName);
	CarValCook=getCookie(CarValCookie);
	if(ExistingCookie!=null){
		cs+=ExistingCookie;	 									 
		//grab the current value of the cart
		cartvalue=parseFloat(CarValCook); 
	} 
	
	if(cs.length>=MAX_CS_LEN){
		alert("Your cart is full, this item cannot be added. Please submit your cart for saving, then you may return here to continue shopping.");
		return;
	}	
	//get outta here if no value
	if(frm.fquantity.value==null || frm.fquantity.value=='')return; 
	//add a product delimiter character before adding a new product
	if(cs.indexOf(-1)!=ProdDelim && cs!='')cs+=ProdDelim; 
	//loop through all elements and grab the ones that are not
	//id or price or quantity
	for(var i=0;i<frm.length;i++){	
		var e=frm.elements[i];
		var ex_val = e.value;
		var n = e.name.toLowerCase();
	
		if(e.type!='button' && e.name.toLowerCase()!='fprice' && e.name.toLowerCase()!='fquantity' 
							&& e.name.toLowerCase()!='fproductid'){			
			if(frmAdds.indexOf(-1)!=',' && frmAdds!='')frmAdds+=',';
				var data;
				//due to differences in browsers I need to access select
				//elements differently based on browser
				if(e.type=='select-one') data=ReturnSelectData(e); 
				else{
					data=ex_val;
					//data=e.value;
				}
				frmAdds+=e.name+'='+data;
		}
	}
	//based on the action passed I will now either add the item chosen
	//to the cart, or subtract from it.
	if(addItem==true){	
		//First add this to cart value total
		cartvalue+=(parseFloat(frm.fprice.value)*parseInt(frm.fquantity.value)); 
		//then add the actuall prodcut id and quantity
		cs+='fid='+frm.fproductid.value+',q='+frm.fquantity.value;
		//if there were extras with this order add them
		if(frmAdds!='')cs+=','+frmAdds;	
		//replace long names with shorter ones so more can fit in the querystring
		cs=ReplaceValues(cs);	
		
		var items=cs.split(ProdDelim);
		//CurrentCartValue=cartvalue;
		ReloadItems(items,''); //reload items into the cart box			
		window.status ='Item #'+frm.fproductid.value+' with quantity of '+frm.fquantity.value+' added!!!';		
	}
	else{
		var ncs='';	
		ItemToRemove='fid='+frm.fproductid.value+',q='+frm.fquantity.value;
		if(frmAdds!='')ItemToRemove+=','+ReplaceValues(frmAdds);
		//make sure that the cookie actually contains the item being removed
		if(cs.indexOf(ItemToRemove)!=-1){
			//only subtract the amount from cart if actually incart		
			cartvalue-=(parseFloat(frm.fprice.value)*parseInt(frm.fquantity.value)); //subtract this from cart	
			var items=cs.split(ProdDelim); //make array			
			var AlreadyRemovedItem=false;		
			//loop through and rebuild cookie skipping the item to remove
			for(i=0;i<=items.length;i++){
				if(items[i]!=null){
					if(items[i]==ItemToRemove && AlreadyRemovedItem!=true){
						AlreadyRemovedItem=true;
					}
					else{
						if(ncs.indexOf(-1)!=ProdDelim && ncs!=null)ncs+=ProdDelim;
						ncs+=items[i];
					}
				}
			}
			if(ncs==ProdDelim)ncs='';
			cs=ncs;
			//CurrentCartValue=cartvalue;
			ReloadItems(items,ItemToRemove); //reload items into the cart box
			window.status ='Item #'+frm.fproductid.value+' with quantity of '+frm.fquantity.value+' removed!!!';
		}		
	}	
	
	FormatCartVal(cartvalue); //set status				
	//reset the cookie
	cs=ReplaceValues(cs);
	setCookie(CookieName,cs,1);	 
}  

/*
	Function: ReturnSelectData
	Purpose: Netscape and IE handle the avenue of getting select data differently
				so determine browser type then use appropriate avenue
*/
function ReturnSelectData(e){
	if(navigator.appName=='Netscape') 
	{   	
 		var s=e.selectedIndex;
 		var data=e.options[s].value;
 	}
 	else
 	{
 		var data=e.value;
 	}
	return data;
}

/*
	Function: TestBrowser
	Purpose: To ensure compatible browser
*/
function TestBrowser(){
	var browser= new Object();
	browser.version=parseFloat(navigator.appVersion);
	browser.isNavigator=false;
	browser.isIE=false;
	if(navigator.appName.indexOf('Netscape')!=-1)
		browser.isNavigator=true;
	else if(navigator.appName.indexOf('Microsoft')!=-1)
		browser.isIE=true;
	
	if(browser.isNetscape==true && browser.version<4.5){
		var msg;
		msg='This shopping cart requires a more recent version of browser';
		msg+='than you are currently using. Please visit http://www.netscape.com';
		msg+=' and upgrade your browser to at least version 4.5.';
		GoodBrowser=false;
		alert(msg);
	}
	else if(browser.isIE==true && browser.version<4.0){
		var msg;
		msg='This shopping cart requires a more recent version of browser ';
		msg+='than you are currently using. Please visit http://www.microsoft.com';
		msg+=' and upgrade your browser to at least version 4.0.';
		GoodBrowser=false;
		alert(msg);
	}	
	else if((browser.isNetscape==true && browser.version>=4.5) ||
				(browser.isIE==true && browser.version>=4.0)){
		GooBrowser=true;
	}
}

/*
	Function: TestCookie
	Purpose: Test whether or not the client accpets cookies
*/
function TestCookie(){
	if(CookieTest==-1){
		if(!doTest()){ //test to see if they accept cookies
			alert('Your browser currently does not accept cookies. You cannot use this cart unless you turn the cookies option on in your browser.');
			return false; //end
		}
		else{
			CookieTest=1;
			return true;
		}
	}
}

/*
	Function: FormatCartVal
	Purpose: To give a nice money look to the cart value
*/
function FormatCartVal(cartval){
	var val,zeros='';			  
	var cartvalue=''+cartval;  		
	if(cartvalue==null)return;										
	if(cartvalue.indexOf('.')==-1){
		cartvalue=cartvalue+'.00';
	}
	else{
		val = cartvalue.substring(cartvalue.indexOf('.'),cartvalue.length)
		if(val.length!=3){
			for(var i=0;i<=(2-val.length);i++)zeros+='0';
		}
		cartvalue+=zeros;
	}
	if(UVCR)document.usercart.cartvalue.value=cartvalue;

	CurrentCartValue=cartvalue; //keep track of this total
	setCookie(CarValCookie,CurrentCartValue,1);
}	

/*
	Function: ResetCartValue
	Purpose: Fire when the box that contains the cartvalue is changes by the user
				used to keep constant the value of the cart
*/
function ResetCartValue(){
	if(UVCR)document.usercart.cartvalue.value=CurrentCartValue;
}

/*
	Function: ReturnFriendName
	Purpose: Give nice names to ugly references
	Args: s reference that needs a nice name
*/
function ReturnFriendName(s){
	switch(s.toLowerCase()){
		case 'q':
			return 'Qty';
			break;
		case 'fid':
			return 'ProdID';
			break;
		case 'fd':
			return 'Desc';
			break;
		default:
			return s;
	}		
}

/*
	Function: ReplaceValues
	Purpose: Replace long names in function with shorter ones
*/
function ReplaceValues(s){
	//s=s.toLowerCase();
	s=strReplace(s,'fquantity','q');
	s=strReplace(s,'fproductid','fid');
	s=strReplace(s,'foption1value','fo1v');
	s=strReplace(s,'foption1name','fo1n');
	s=strReplace(s,'foption2value','fo2v');
	s=strReplace(s,'foption2name','fo2n');
	s=strReplace(s,'foption3value','fo3v');
	s=strReplace(s,'foption3name','fo3n');
	s=strReplace(s,'fdesc','fd');
	
	return s;
}

/*
	Function: strReplace
	Purpose: Replace all occurances of sItemToFind, in sData, with sItemToReplace
	Args: 3, sData = actual string to do replacing in
			sItemtoFind = item wanting replaced
			sItemToReplace = item to stick into place of prev item
*/
function strReplace(sData,sItemToFind,sItemToReplace){
	if(sData.indexOf(sItemToFind)==-1)return sData;
	var start, end, lenItemToFind, firstHalf, secondHalf;
	do{
		start=sData.indexOf(sItemToFind);
		end=start+sItemToFind.length;
		firstHalf=sData.substring(0,start);
		secondHalf=sData.substring(end,sData.length);
		sData=firstHalf+sItemToReplace+secondHalf;
	}
	while(sData.indexOf(sItemToFind)!=-1);
	return sData;
}

/*
	Function: ReloadItems
	Purpose: Reload the optional visual cart info.
	Args: sData this is an array of cart items, ItemToAvoid this if it has data in it
			will not be added to the cart
*/
function ReloadItems(sData,ItemToAvoid){
	var item,part,line='\n'+'-----------------'+'\n';	
	var skipped=false;		
	var option=false;
	var numItems=0;
	var AlreadyRemovedItem=false; //incase they add two of the same item, only remove one instance
	
	if(document.usercart==null){
		UVCR = false;
	}
	else{
		UVCR = true;
	}
	for(var i=0;i<=sData.length;i++){
		if(sData[i]==ItemToAvoid && AlreadyRemovedItem!=true){ 
			//only remove an item once, before implementuing this if there were 2 dupe items
			//it would remove both	
			AlreadyRemovedItem=true;
		}
		else{
			if(sData[i]!=null){				
				item=sData[i].split(',');	
				var OptionNames=new Array();
				var OptionValues=new Array();
				var nameCount=-1;valCount=-1;				
				for(var j=0;j<=item.length-1;j++){
					part=item[j].split('=');			
					//***************************
					// This section takes care of detecting
					// options and marries the name with the value
					//***************************
					var n=part[0].toLowerCase();	
					//get the number of items
					if(n==('q'))numItems+=parseInt(part[1]);
					option=false;
					if(n.indexOf('fo')!=-1 && n.indexOf('n')!=-1 && n.length==4){
						nameCount++;
						OptionNames[nameCount]=part[1];
						option=true;
					}
					if(n.indexOf('fo')!=-1 && n.indexOf('v')!=-1 && n.length==4){
						valCount++;
						OptionValues[valCount]=part[1];
						option=true;
					}
					// END option detection
					
					if(part[1]==null){
						skipped=true;
						continue;
					}
					else skipped=false;
					if(option==false){
						if(UVCR)document.usercart.ta.value += ReturnFriendName(part[0])+'='+part[1]+' '; 
					}
										 
				}	
				//Once all options have been captured and all other data printed
				//to box, now print the married options and values
				for(j=0;j<=nameCount;j++){
					if(UVCR)document.usercart.ta.value += FirstLetterCap(OptionNames[j])
										+'='+FirstLetterCap(OptionValues[j])+' '; 		
				}				
				if(skipped==false)if(UVCR)document.usercart.ta.value += line;
			}
		}
	}	
	return numItems;		
}

/*
	Function: FirstLetterCap
	Purpose: Capitolize the first letter of a word
*/
function FirstLetterCap(s){
	var fl,rest;
	fl=s.substring(0,1);
	rest=s.substring(1,s.length);
	s=fl.toUpperCase()+rest;
	return s;
}

/*
	Function: SubmitCart
	Args: 2, the merchant ID, and the return URL
	Purpose: To build the query string based upon the cookie. 
			 Cookie is destroyed upon cart submission.
*/					   
function SubmitCart(MerchID,ReturnURL){
	var cs, qs,f='fproductid=',q='fquantity=';	 //CookiesString,QueryString,FID String,QuantityString
	var fid = new Array();
	var quant = new Array();
	var item = new Array();
	
	cs=getCookie(CookieName);
	//make sure there is something in the cart to send
	if(cs==null){
		alert('You have no items in your cart. Please select some items before submitting.');
		return;
	}
	
	qs='mMerch_ID='+escape(MerchID)+'&'+'fReturnURL='+escape(ReturnURL)+'&ITEMS='+cs;		
	mURL = 'www.securepay.com/easyshop/addprodnew.asp?js=yes&'+qs;
	// destroy cookie
	ClearCart();
	window.status ='Submitting cart one moment please ... ';
	if(UVCR)document.usercart.ta.value='Submitting ... \n One moment please.';	
	//alert(mURL);
	parent.location.href='https://' + mURL;		
} 

/*
	Function: ClearCart
	Purpose: Give the user to completely clear out the cart. Called automatically
				when the user submits the cart.
*/
function ClearCart(){
	DeleteCookie(CookieName);
	DeleteCookie(PopUpCookie);
	if(UVCR)document.usercart.ta.value='';
	if(UVCR)document.usercart.cartvalue.value='0';
	CurrentCartValue=0;
	window.status ='Cart empty!';
}

/*
	Function: CartInfo
	Purpose: Detail Description of cart
	Args: Path to page
*/
function CartInfo(path,frm)
{	
	var iHeight=310;
	//var CookieValue='';
	//CookieValue=getCookie(CarValCookie);//CurrentCartValue;		
	//alert(CookieValue);
	//setCookie(PopUpCookie,CookieValue,1);
	NW=window.open(path,'NW','toolbar=no,status=no,scroll=yes,width=540,height='+iHeight+',left=50,top=50');	
}

/*
	Function: LoadPopUp
	Purpose: Loads the popup cart box with data
*/
function LoadPopUp(){
	var ExisitingCookie, CartVal, bc, tc, vals;
	var cs='', numItems;
	ExistingCookie = getCookie(CookieName);
	CartVal = getCookie(CarValCookie);
	if(ExistingCookie!=null){
		cs+=ExistingCookie;	 
		var items=cs.split(ProdDelim);
		numItems=ReloadItems(items,''); //reload items into the cart box	
		document.usercart.cartvalue.value=CartVal;
		DeleteCookie(PopUpCookie);
		document.usercart.num.value=numItems;	
	}
	else{
		document.usercart.ta.value='Cart Empty, please select some items before viewing cart details.';
	}
		
}

/*
	Function: getQS
	Purpose: Retrieve the querystring
*/
function getQS(){
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for(var i=0;i<pairs.length;i++){
		var pos=pairs[i].indexOf('=');
		if(pos==-1)continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname]=unescape(value);
	}
	return args;
}


//-------------------------------JS for Cookies-----------------------------

/*
	Function: DeleteCookie
	Purpose: TO clear cookie from users cache
	Args: 1, Cookie name
*/
function DeleteCookie(CookieName){
	setCookie(CookieName,'',-50);
}
	
/*
	Function: setCookie
	Putpose: Actually set the cookie on the users machine
	Args: 3, Name=name of cookie, value=value of cookie, days=time to expire
*/
function setCookie(name, value, days) {
   var expire = new Date();
   expire.setTime(expire.getTime() + (60*60*24*days*1000));
   document.cookie = name + "=" + escape(value) + ' ; path = /'
   + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}

/*
	Function: getCookie
	Purpose: Retrun the cookie on user machine to calling function
	Args: 1, Name=name of cookie
*/
function getCookie(Name) {
	var search = Name + "=";
	if (document.cookie.length > 0) { 
		offset = document.cookie.indexOf(search);
		if (offset != -1) { 
			offset += search.length;         
			end = document.cookie.indexOf(";", offset);         
			if (end == -1)end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		} 
	}
	else
		return null;
}

/*
	Function: doTest
	Purpose: Test to see if users browser accepts cookie. Do this by
				setting a temp cookie and then trying to read it back.
*/
function doTest()
{
	//expiry for test cookie
	var oneDay= 1*24*60*60*1000;
	var expDate = new Date();
	expDate.setTime (expDate.getTime() + oneDay);
	var cookieExpires = expDate.toGMTString();
	//set temprorary cookie to make sure they accept cookies
	document.cookie="verifyCookie=test; expires="+cookieExpires;
	//check to see if ANY cookies exist, including the one you just set
	if (document.cookie.length>0){
		//now set for deletion the test cookie
		document.cookie="verifyCookie=CLEAR; expires=Sun, 09-Nov-97 01:00:00 GMT";
		return true;
	}
	else 
		return false;
}
//-------------------------------END JS for Cookies------------------------
