//<!--- Hide from old browsers not supporting JavaScript that need to ignore this code ---

//==============================================================================
// This code implements the functionalities of the shopping cart used to order
// items on the HTML web pages. It uses an array of objects to store the
// items ordered. The array is then accessed formatted and sent to the server. 
//
// Name:		Cart Module
// Author:		Enrico Messana Calgary-Alberta Copyright@ 2008-2009
//
// Revisions:	Sep 15, 2007	First release with basic cart
//			Nov 24, 2007	Added shipping charge selection
//			Jan 04, 2008	Corrected some comments
//			Feb 27, 2008	Added item not available alert
//			Apr 13, 2008	Added page name handling
//			Mar 29, 2009    Added Local shipping charges
//
// Latest Issue:	April 13, 2008
// Language:	JavaScript
//
//==============================================================================

//==============================================================================
// Set of module variables used to compute the amount of items ordered
// 
var order = new Object();	// array of objects used to store the orders in
var root  = new Object();	// object containing the elements used by the cart
var strn  = new Array();	// string array passed to the cart server
var orderIndex;			// order array index
var index = 0;			// used to index the order objects

// Accessory variables
var on    = true;
var off   = false;

// formats PP's server window. Latest April 11, 2008
var winpar =	"width=850, height=650, scrollbars, resizable, status";

// URL of user-specific business page
root.busId    = "sales@everythingbutthecake.ca";	// ebtc id
// URL used for cancel return path
root.canc     = "http://www.everythingbutthecake.ca/payment_cancel.htm";
root.hide     = "hidden";	// type="hidden"
root.mtd      = "post";		// 
root.cmd      = "_cart";	// 
root.style    = "ebtc";		// ebtc page style
root.bn       = "PP-ShopCartBF"; // 
root.curr     = "CAD";		// default currency code (or null)
root.add      = "1";		// default number of items added 
root.itemName = " ";		// place holder for item name

//==============================================================================


//==============================================================================
// Method name:	setPageName
//
// Revision state:
//	Apr 13, 2008	First issue
// 
// Description:
// Saves the page into the root object. The HTML page calls this method during 
// the page load to pass the item category name to the cart for identification. 
// The page name will appear in the cart table to identify the item category.
//
// Notes: n/a
//
//==============================================================================
function setPageName (name)
{
  root.itemName = name;
}

//==============================================================================
// Method name:	orderItems
//
// Revision state:
//	Sep 15, 2007	First issue created basic cart
//	Jan 04, 2008	Corrected some comments
//	Feb 27, 2008	Added item not available alert
// 
// Description:
// This method is called by the HTML page every time the customer changes the
// purchase quantity of an item.
// It creates and object referenced by the form parameter containing quantity 
// ordered. Price and description are passed as parameters to the method.
// The form parameter is used to reference the objects in the array. If 
// a form is passed referring to an existing object than this method needs to
// delete the existing object and create a new one with the new quantity 
// entered by the customer, and passed to this method.
//
// Notes: If price=0 is passed then the method will alert the customer that
// the item selected is not available.
//
//==============================================================================
function orderItems(form, price, desc)
{
	var i =0;

	// if price = 0 then product not available
	if ( price == 0)
	{
		form.reset();	// clears the quantity entered in the input box of the HTML page
		alert ("Sorry, this item is not available at the moment. Thank you.");
		return;
	}

	// check if this object already exists. If it does, it needs to be deleted. 
	// The customer is changing the item quantity in input.  A new instance of
	// object will be created
	for ( i in order )
	{
		if ( order[i].form == form )
		{
			delete order[i];	// delete the object from the array

			// create the new object and save the relevant information
			order[i] = new Object();
			order[i].desc = desc;
			order[i].qty  = form.itemQty.value;
			order[i].amt  = price;
			//save form object to clear quantity input after submission 
			order[i].form = form;
			return
		}
	}
	
	// This object does not exist create a new one
	order[index] = new Object();
	order[index].desc	= desc;
	order[index].qty  = form.itemQty.value;
	order[index].amt  = price;
	//save form object to clear quantity input after submission 
	order[index].form	= form;

	// increment the index to the next new object
	index++;
}


//==============================================================================
// Method name:	sendCart
//
// Revision state:
//	Sep 15, 2007	First issue created basic cart
//	Nov 24, 2007	Added shipping charge selection
//  Mar 29, 2009	Added local shipping charges
// 
// Description:
// For each item saved in the object array it formats the order string and 
// sends it to the cart on the server side. It uses a secure connection
// (i.e. 'https://') to keep the information passed safe.
// It uses the shipping parameter to set the shipping charges if required.
// If shipping=0 then no shipping is charged.
//
// Notes: This method uses wrtiteToServer method to send the order strings 
// to the server.
//
//==============================================================================
function sendCart(shipping)
{
	var localShipping = 0;	//indicates that local shipping is charged
	var i=0;				//iterator of order object array
	var j=0;				//index of ordered items

	for ( i in order ) // send all valid data
	{
		if ( order[i].qty > 0 )
		{
			// fill the string
			strn[j] = "https://www.paypal.com/cgi-bin/webscr?" + "&method=" + root.mtd
				+ "&target=paypal"					// target
				+ "&cmd="			+ root.cmd		// cart command
				+ "&business="		+ root.busId	// business ID
				+ "&cancel_return="	+ root.canc		// cancel return page
				+ "&page_style="	+ root.style	// page style
				+ "&bn="			+ root.bn		// bn
				+ "&currency_code="	+ root.curr		// currency
				+ "&add="			+ root.add		// add or display
				+ "&item_name="		+ root.itemName;// item name

			// fill string with order details
			strn[j] = strn[j]
				+ "&on0="			+ "details"
				+ "&os0="			+ order[i].desc	// item description
				+ "&quantity="		+ order[i].qty	// item quantity
				+ "&amount="		+ order[i].amt;	// item unit cost

			// no shipping charged if purchase within Calgary and higher than $50.00 CAD
			// On March 30, 09 shipping changed. Charged $8.00 for Calgary city limits
			if ( shipping == localShipping )
			{
				//Check if the shipping charged cookie is present
				//var c_start = document.cookie.indexOf("ebtc_shipping=");
				//if (c_start == -1)  //Cookie not present
				cookieName = getCookie ('ebtc_shipping');
				if (cookieName == null || cookieName == "")
				{	// Cookie not present
					// this set the local shipping charges
					strn[j] = strn[j] + "&shipping=8";
				
					//set a cookie to remember within pages that the shipping has been charged
					//This cookie is deleted when the purchase transaction is closed
					var exp = new Date();		//Get current date
					//                             h   min sec   ms
					var expTime = exp.getTime() + (2 * 60* 60 * 1000);  //Corresponds to 2 hours in milliseconds
					exp.setTime(expTime);
					//document.cookie = "ebtc_shipping=yes; expires=" + exp.toGMTString();
					//Creating a cookie without expiry date forces the browser to consider it temporary
					//and to discard it whenever the browser application is closed 
					document.cookie = "ebtc_shipping=yes";
					//alert ("Cookie saved");
				}
				else
				{	//cookie present. Do not add further shipping charges
					strn[j] = strn[j] + "&shipping=0";
					//alert ("Cookie already there");
				}
			}
			order[i].form.reset();	// clears the quantity in the input box of the HTML page
			delete order[i];	// deletes the element from the array of objects
			
			j++;	// increment number of ordered items
		}
	}
	// Add "End Of Array" string after last element filled
	strn[j] = "End Of Array";

	// check if at least one item has been purchased	
	if ( j > 0 )
	{
		var pWindow = window.open ( strn[0], "paypal", winpar );
		//pWindow.status='Safe access to your PP shopping cart from ebtc.ca';
		// set array index to 1
		orderIndex = 1;
		
		// This is the first iteration of writeToServer. The server needs more
		// time to setup the connection session
		setTimeout("writeToServer()", 3500);	// wait 3.5 secs
	}
	else	// if not, send an alert
	{
		alert ("Please enter the quantity of one or more items you want to purchase. Thank you.");
	}
}


//==============================================================================
// Method name:	writeToServer
//
// Revision state:
//	Sep 15, 2007	First issue created basic cart
// 
// Description:
// This method is called by sendCart() for the first iteraion. It then calls
// itself until the last string of the order is sent to the cart server. 
// It opens a new window if a cart window is not alredy opened.
// A 1 second timer is set to allow the cart server to receive the order
// string and add it to the cart table.
//
// Notes: This method iterates trhtough itself to send the order strings 
// to the PayPal server.
//
//==============================================================================
function writeToServer()
{
	// If strn[ordrIndex] = "End Of Array" then stop looping
	if ( !strn[orderIndex].match ( "End Of Array" ))
	{
		var pWindow = window.open ( strn[orderIndex], "paypal", winpar );
		//pWindow.status='Safe access to your PP shopping cart from ebtc.ca';
		orderIndex++;
		
		setTimeout("writeToServer()", 1000);	// wait 1 sec
	}
}


//==============================================================================
// Method name:	deleteShippingCookie
//
// Revision state:
//	Mar 30, 2009	Deletes the local shipping charges cookie
// 
// Description:
// This method deletes the cookie generated to track the local shipping
// charges. Once the customer completes the purchase order this method
// is called and another local purchase session can be properly initialized.
//
//==============================================================================
function deleteShippingCookie()
{
	//Check if the shipping charged cookie is present
	cookieName = getCookie ('ebtc_shipping');
	if (cookieName != null || cookieName != "")
	{	// Cookie present
		// set the cookie expiry date earlier to current date so the browser deletes it
		document.cookie = "ebtc_shipping=yes; expires=Thu, 02-Mar-2009 00:00:01 GMT";
		//alert ("Cookie deleted");
	}
}


//==============================================================================
// Method name:	getCookie
//
// Revision state:
//	Mar 30, 2009	Deletes the local shipping charges cookie
// 
// Description:
// This function checks if a cookie is stored at all in the document.cookie object.
// If the document.cookie object holds some cookies, then checks if the cookie
// name entered as aparameter is present. If the cookie is found, then return 
// the value, if not - return an empty string.
//
//==============================================================================
function getCookie(c_name)
{
   if (document.cookie.length > 0)
   {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start != -1)
      { 
         c_start = c_start + c_name.length + 1; 
         c_end = document.cookie.indexOf (";",c_start);
         if (c_end == -1)
            c_end = document.cookie.length;
         return unescape(document.cookie.substring(c_start,c_end));
      } 
   }
   return "";
}


//==============================================================================
// Method name:	viewCart
//
// Revision state:
//	Sep 15, 2007	First issue created basic cart
// 
// Description:
// Allows retrieving the shopping cart table from the server and show it to
// the customer.
// It opens a new window if a cart window is not alredy opened.
//
// Notes: n/a.
//
//==============================================================================
function viewCart()
{
  var strn = new Array();

	strn = "https://www.paypal.com/cgi-bin/webscr?&method=post"
		 + "&business=sales@everythingbutthecake.ca"	// business ID
		 + "&cmd=_cart"					// cmd _cart
		 + "&display=1";				// display cart content

	window.open ( strn, "paypal", winpar );
}

// Used for browsers not supporting JavaScript //--->
