/* VITW settings  Authorize.net allows 30 items max */
var MaxCartItems = 30;
var CookieNamePrefix = "VitwCart0418_";
var CookieLifeDays = 32;

/*
 Low level cookie functions 
*/
function createCookie(name,value,days) 
{
    if(days > 0) 
    {
     	var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else 
    {
    	var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) 
    {
    	var c = ca[i];
        while (c.charAt(0)==' ') 
        {
        	c = c.substring(1,c.length);
        }
        if(c.indexOf(nameEQ) == 0) 
        {
        	return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

/* 
based on media mailing rates Spring 2007
http://www.usps.com/rates/media-mail-rates.htm
*/
function CalcShipping(onces)
{
	cost = new Array(11);
	
	if(onces == 0)
	{
		return 0.00;  // No shipping on donations
	}
	cost[0] = 2.23;  // 0..15 onces 
	cost[1] = 2.58;  // 1 pound to less than 2lbs
	cost[2] = 2.93;
	cost[3] = 3.28;
	cost[4] = 3.63;
	cost[5] = 3.98;
	cost[6] = 4.33;
	cost[7] = 4.68;
	cost[8] = 5.03;
	cost[9] = 5.38;
	cost[10]= 5.73; 
	cost[11]= 6.08; 
	cost[12]= 6.43; 
	cost[13]= 6.78; 
	cost[14]= 7.50; 
	cost[15]= 9.50; // 15 or more pounds we cap here

	lbs = parseInt(onces/16);
	if(lbs < 0)
	{
		lbs = 0;
	}
	if( lbs > 15)
	{
	    r = cost[15]
        r = r + ( (lbs-15) * .97)
        if(r > 55)
        {
            r = 55
        }
	}
    else
    {
	    r = cost[lbs]
    }
	return r;
}


/*
Cookie Shopping cart has colon delimters as
ID:Qty:Price:What:Descr:
*/


/*
  return array indexed by Raw, ID Price Qty, Descr
*/
function GetCookieArray(item) 
{
	s1 = readCookie(CookieNamePrefix + item);
	if(s1 != "undefined" && s1 != null)
	{
		ss = s1.split(":")
		r = new Array(6);
		r['Raw'] = s1;
		r['ID']  =   ss[0];
		r['Qty']  =  ss[1];
		r['Price'] = ss[2];
		r['Onces'] = ss[3];
		r['What']  = ss[4];
		r['Descr'] = ss[5];
		return r;			
  	}
  	return null;
}


function SetCookie(item, value) 
{
	createCookie(CookieNamePrefix + item, value, CookieLifeDays);
}


function DeleteCookie(item) 
{
	createCookie(CookieNamePrefix + item);
}



function AddToCart(ID,Qty,Price,Onces,What,Descr) 
{
 	if(Qty <= 0) 
 	{
     	rc = alert('The Quantity must be greater than 0');
   	}

	if(Price < 1.00)
	{
     	rc = alert('The Price must be at least one dollar.');
	}

	for(ItemNum = 1; ItemNum<=MaxCartItems; ItemNum++) 
	{
    	if(ItemNum == MaxCartItems) 
    	{
        	alert('Maximum of '+MaxCartItems+' different items can fit in the shopping cart, please go to the Checkout Counter and submit your order. Then empty your cart and shop some more later.');
        }
        else 
        {
            CookieValue = GetCookieArray(ItemNum);
            if(CookieValue == null) 
            {	/* ID:Price:Quantity:What:Descr */
                CookieValue = ID+":"+Qty+":"+Price+":"+Onces+":"+What+":"+Descr+":";
                SetCookie(ItemNum,CookieValue);
                a = GetCookieArray(ItemNum);
                if(a == null || a['Descr'] != Descr)
                {
                	alert("You must enable javascript to shop.");
                	return false;
                }
				msg =  Descr + " has been added to your shopping cart.";
				alert(msg);
                break;
          	}
      	}
  	}
}


function GetCartTable() 
{
        var s = '<h3>Resources</h3><p><br><br>';
        s += '<h4>View Cart / Edit Quantities</h4>';
		s += '<font color="#DAA520" size=2 face="Verdana">';

        s += '<table border="01" rules="all" frame="border" cellspacing="20" cellpadding="2" bgcolor="#000000" color="#DAA520">';
        s += '<tr><td align="left">#</td>';
        s += '<td align="left"><b>ID</b></td>';
        s += '<td align="left"><b>Type</b></td>';
        s += '<td align="left"><b>Description</b>&nbsp;&nbsp;</td>';
        s += '<td align="left"><b>Quantity</b></td>';
        s += '<td align="left"><b>Price Each</b></td>';
        s += '<td align="left"><b>Price Total</b></td>';
        s += '<td align="left"><b>Delete</b></font></td></tr>';

		var itemized = '';
		var totOnces = 0;
		var totPrice = 0;
		var LineNum = 1;
        for(ItemNum = 1; ItemNum<=MaxCartItems; ItemNum++)
        {
                var a = GetCookieArray(ItemNum);
                if(a != null)
                {
					ID = a['ID'];
					Qty = a['Qty'];
					Price = a['Price'];
					Onces = a['Onces'];
					What  = a['What'];
					Descr = a['Descr'];

					ItemTotal = (eval(Price*Qty));
					totOnces +=  (eval(Onces*Qty));
					totPrice = totPrice + ItemTotal;

                    FItemTotal = FloatFormat(ItemTotal,2);
                    Price2d = FloatFormat(Price,2);
                    
                    s += "<tr><td>"+LineNum+"</td>";
                    s += '<td align="left">'+ID+'</td>'
                          + '<td align="left">'+What+'</td>'
                          + '<td align="left">'+Descr+'</td>'
                          + '<td align="left">' + controlSelect(ItemNum, Qty) + '</td>'
                          + '<td align="left">'+Price2d+'</td>'
                          + '<td align="left">'+FItemTotal+'</td>'
                          + '<td><a href="javascript:RemoveItem('+ItemNum+');"><img src="/images/cart_remove.png"></a></font></td>'
                          + '</tr>';
					LineNum++;
                }
        }

        FtotPrice = FloatFormat(totPrice,2);
        s += '<tr><td colspan=6><b>Sub Total</b></td>';
        s += '<td align=right>'+FtotPrice+'</td>';
		s += '<td><input type="image" alt="Empty all items in shopping cart" src="/images/cancel.png" onclick="EmptyCart();"></td></tr>';       

        Shipping = 0;
        if(totOnces > 0)
        {
    		Shipping = .55 + CalcShipping(totOnces + 9);  /* Box price + Box Weight */
        }
        FtotOnces = FloatFormat(totOnces,1);
		FShipping = FloatFormat(Shipping,2);
		FGrandTotal = FloatFormat(totPrice + Shipping,2);

		s += '<tr><td colspan=6><b>Shipping / Handling</b></td><td align=right>'+FShipping+'</td></tr>';
		s += '<input type="hidden" name="Shipping" value="'+FShipping+'">';

		s += '<tr><td colspan=6><b><font color="#EEEEEE">Total to be billed on credit card</font></b></td><td align=right><font color="#FFFFFF">$ '+FGrandTotal+'</font></td></tr>';
		s += '</table>\n<br/><P>';
		s += '<input type="hidden" name="x_amount" value="'+FGrandTotal+'">';
        s += '</table></font>';
        s += '<br><p>';

		/**** SUBMITTED FORM BEGINS ****/
		
		s += '\n\n<form action="https://secure.authorize.net/gateway/transact.dll" method="post" name="OrderForm">';
		s += '<input type="hidden" name="x_description" value="Voice in the Wilderness Ministries - www.Voice-Wilderness.org">';
		s += '<input type="hidden" name="x_state" value="">'; 
		s += '<input type="hidden" name="x_method" value="CC">'; 
		s += '<input type="hidden" name="x_type" value="AUTH_CAPTURE">'; 

		s += '<input type="hidden" name="x_Version" value="3.0">';
		s += '<input type="hidden" name="x_Show_Form" value="PAYMENT_FORM">';

		s += '<input type="hidden" name="x_type" value="AUTH_CAPTURE">'; 
		s += '<input type="hidden" name="x_test_request" value="FALSE">'; 
		s += '<input type="hidden" name="x_tax_exempt" value="TRUE">'; 
		s += '<input type="hidden" name="x_Login" value="tms48bce2a76">';
		s += '<input type="hidden" name="x_receipt_link_url" value="http://www.voice-wilderness.org/index.php">';
		s += '<input type="hidden" name="x_receipt_link_method" value="LINK">';
		s += '<input type="hidden" name="X_logo_url" value="http://www.voice-wilderness.org/images/chicago101_authNet.jpg">';

		DASH = '----------------------------------------------------------';
		LineNum = 1;
        for(ItemNum = 1; ItemNum<=MaxCartItems; ItemNum++)
        {
                var a = GetCookieArray(ItemNum);
                if(a != null)
                {
					ID = a['ID'];
					Qty = a['Qty'];
					Price = a['Price'];
					Onces = a['Onces'];
					What  = a['What'];
					Descr = a['Descr'];

					ItemTotal = (eval(Price*Qty));
					totOnces +=  (eval(Onces*Qty));
					totPrice = totPrice + ItemTotal;

                    FItemTotal = FloatFormat(ItemTotal,2);
                    Price2d = FloatFormat(Price,2);

					/* Merchant Defined Fields must start with (x_) and will be E-Mailed to Admin so we capture the order contents */
					LineNumS = "" + LineNum;
					if(LineNumS.length < 2)
					{
						LineNumS = "0" + LineNumS;
					}
					s += '<input type=hidden name="x_VITW_DASH'+LineNumS+'" value="'+DASH+'">';
					s += '<input type=hidden name="x_VITW_'+LineNumS+'" value="Stock:'+ID+' : '+What + ' : ' + Descr + ' | Quantity='+Qty+' x $'+Price+' = '+FItemTotal+'">';

					s += '<INPUT TYPE="HIDDEN" NAME="x_line_item" VALUE="item'+LineNum+'<|>'+ID+'<|>'+Descr+'<|>'+Qty+'<|>'+Price+'<|>N">';

					LineNum++;
                }
        }

		/* Merchant Defined Fields (x_) for totals */
		s += '<input type=hidden name="x_VITW_SUBDASH"   value="'+DASH+'">';
		s += '<input type=hidden name="x_VITW_WEIGHT"    value="Estimated Weight  '+FtotOnces+' oz." >';
		s += '<input type=hidden name="x_VITW_SUBTOTAL"  value="Subtotal Price        $'+FtotPrice+'">';
		s += '<input type=hidden name="x_VITW_SHIPPING"  value="Shipping / Handling  $'+FShipping+'">';
		s += '<input type=hidden name="x_VITW_BILLED"    value="Billed on Credit Card $'+FGrandTotal+'">';
		s += '<input type=hidden name="x_VITW_ENDDASH"   value="'+DASH+'">';
		
		if(FGrandTotal > 0)
		{
			s += '<input type="hidden" name="x_amount" value="'+FGrandTotal+'">';
			s += '<input type="submit" name="CheckOut" value="Proceed to Secure Check Out">';
		}
		s += '</form><!--EOC-->';

		return s;
}

function controlSelect(item,Qty)
{
	s = '<select name="Qty_'+item+'" OnChange="javascript:QtyChange('+item+',this[this.selectedIndex].value);" size="1">';
	
	for(i=1; i<=30; i++)
	{
		sel = "";
		if(Qty == i)
		{
			sel = " SELECTED ";
		}
		s += '<option'+sel+' value="'+i+'">'+i+'&nbsp;&nbsp;&nbsp;</option>';
	}
	s += '</select>';
	return s;
}


function QtyChange(item,Qty)
{
	var a = GetCookieArray(item)
	a['Qty'] = Qty;
	ID = a['ID'];
	Price = a['Price'];
	Onces = a['Onces'];
	What = a['What'];
	Descr = a['Descr'];

	var CookieValue = ID+":"+Qty+":"+Price+":"+Onces+":"+What+":"+Descr +":";
	DeleteCookie(item);
	SetCookie(item,CookieValue);
	DrawViewCartPage();
}

function RemoveItem(itemnum)
{
	var a = GetCookieArray(itemnum)
	descr = a['Descr'];

	if(confirm('Click OK to Remove #'+itemnum+', '+descr) )
	{
		DeleteCookie(itemnum);
		DrawViewCartPage();
	}
}

function EmptyCart()
{
	if(confirm('Click OK to Empty the Shopping Cart by\nRemoving ALL Items?\n\n(Note: This Can NOT Be Undone.)'))
	{
		for(ItemNum = 1; ItemNum<=MaxCartItems; ItemNum++)
		{
			DeleteCookie(ItemNum);
		}
		DrawViewCartPage();
	}
}


function FloatFormat(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 DrawViewCartPage()
{
	var s = '';
	s += GetCartTable();
	s += '<br/><P>';
	s += '<hr><P>';
	s += '<BR><P>';
	document.getElementById('StoreDiv').innerHTML=s;
}






