/**
 * The Javascript methods found in this file make up a set of APIs for the 
 * Sunsetter shopping cart functionality.  Please see the document entitled
 * "Shop_Cart_Functional_Reqs.html" for additional details on how the public
 * methods work.
 * 
 * getItems() -  returns an array of items in the shopping cart
 * getItemQuantity() - returns the quantity for a specified item
 * getItemPrice()  - returns the price for a specified item
 * getItemType() - returns the type for a specified item
 * getItemDescription() - returns the description for a specified item
 * addItem() - adds and items with the specified info to the cart
 * removeItem() - removes the specified item from the cart
 * emptyCart() - removes all items from the cart
 *
 */

// The name of the cookie used to store the shopping cart information
var cartCookieName = "sunsetterCart";

// The number of days to store the shopping cart information in the user's browser
var cartCookieExpiration = 30;

/**------------ PUBLIC APIS --------------------------------------------------------*/

/**
 * This method returns a Javascript array containing Javascript 
 * arrays that contain data for each item in the cart. The returned array only 
 * contains items of the specified type.
 */
function getItems(type) {
	
	// type is optional.  set it to a null string if it wasn't specifioed
	if (type == null) type = "";
	
	// get the shopping cart
	var cart = Get_Cookie(cartCookieName);
	if (cart == null) return null;

	//  parse out each item in the shopping cart string.  check each against the 
	// specified type and add it to the return array if it matches.
	var p = new Parser(cart);
	var a = new Array();
	var i = 0;
	var itemDetails = "";
	while ((itemDetails = p.extract("{", "}", true)) != "") {
		var p2 = new Parser(itemDetails);
		var itemType = p2.extract("type=", ";");
		if ((itemType == type) || (type == "")) {
			a[i] = { "itemid" :      p2.extract("itmid=", ";"),
					  "type" :       itemType,
					  "quantity" :    p2.extract("qnty=", ";"),
					  "price" :       p2.extract("price=", ";"),
					  "description" : p2.extract("desc=", ";") };
		}
		i++;
	}

	// return results
	return a;
	
}

/**
 * Call this method to get the quantity for a specific item
 * id. Returns a null string ("") if the specified item id does not exist.
 */
function getItemQuantity(itemId) {

	// create a Parser with the item details for the specified item
	var p = new Parser(getItem(itemId));
	
	// parse out and return the quantity
	return  p.extract("qnty=", ";");
	
}

/**
 * Call this method to get the price for a specific item
 * id. Returns a null string ("") if the specified item id does not exist.
 */
function getItemPrice(itemId) {

	// create a Parser with the item details for the specified item
	var p = new Parser(getItem(itemId));
	
	// parse out and return the quantity
	return  p.extract("price=", ";");
	
}

/**
 * Call this method to get the type for a specific item
 * id. Returns a null string ("") if the specified item id does not exist.
 */
function getItemType(itemId) {

	// create a Parser with the item details for the specified item
	var p = new Parser(getItem(itemId));
	
	// parse out and return the quantity
	return  p.extract("type=", ";");
	
}

/**
 * Call this method to get the description for a specific item
 * id. Returns a null string ("") if the specified item id does not exist.
 */
function getItemDescription(itemId) {

	// create a Parser with the item details for the specified item
	var p = new Parser(getItem(itemId));
	
	// parse out and return the quantity
	return  p.extract("desc=", ";");
	
}

/**
 * Call this method with an itemId, type and quantity. The itemId 
 * is intended to be a unique identifier for a specific item. The itemId should 
 * be unique for each item addded to the cart. If an item already exists in the 
 * cart with the specified itemId, the new item will not be added and addItem will 
 * return false. Returns true if the item is successfully added.
 */
function addItem(itemId, type, quantity, price, description) {

	// get the value in the sunsetter cart cookie
	var cart = Get_Cookie(cartCookieName);
	if (cart == null) cart = "";
	//alert("cart=" + cart);
	
	// get the info for the specified item id, return false if anything
	// is found.  this means the specified item already exists.  it must
	// be removed before it can be added again.
	var p = new Parser(cart);
  // Remove the item from the cart and we will readd if it already exists.
	var itemDetails = p.extract("{itmid=" + itemId + ";", "}", true);
	
  // Don't return false, just update the qty (sum).
  //if (itemDetails != "") return false;
	if (itemDetails != "") {
    cart = p.text;
    var p2 = new Parser(itemDetails);
		var qty = p2.extract("qnty=", ";");
		var newQty = parseInt(qty) + parseInt(quantity);

    // Readd the item with a new qty.
    cart += createItemDetails(itemId, type, newQty, price, description);
            
//    return false;
  }
  else {
	  // create a key/value string with the specified info using the itemId
	  // and the other information and add the new information to the cart cookie
	  cart += createItemDetails(itemId, type, quantity, price, description);
  }
    
	// set the cookie in the users browser including the new information
	Set_Cookie(cartCookieName, cart, getExpires(cartCookieExpiration));
  	
	// return true since the operation succeeded
	return true;
	
}

/**
 * Call this method with an itemId to remove the specified item 
 * from the cart. Returns true if the item is in the cart and it is successfully 
 * removed. Otherwise returns false.  Returns false if the specified itemId is not
 * found in the cart.
 */
function removeItem(itemId) {

	// get the value in the sunsetter cart cookie
	var cart = Get_Cookie(cartCookieName);
	
	// locate the specified itemId
	// if the specified itemId is not found, return false
	var p = new Parser(cart);
	var itemDetails = p.extract("{itmid=" + itemId + ";", "}", true);
	cart = p.text;
	if (itemDetails == "") return false;
	
	// set the cookie in the users browser using the new cart string that has
	// had the specified item removed from it
	Set_Cookie(cartCookieName, cart, getExpires(cartCookieExpiration));
	
	// return true since the operation succeeded
	return true;
	
}

/**
 * This function clears the shopping cart cookie from the user's browser
 */
function emptyCart() {
	Delete_Cookie(cartCookieName);
}

/**------------ PRIVATE METHODS --------------------------------------------------------*/

/**
 * Call this method to get a specific item
 * id. Returns a null string ("") if the specified item id does not exist.
 */
function getItem(itemId) {

	// get the value in the sunsetter cart cookie
	var cart = Get_Cookie(cartCookieName);

	// if the cart does not have any data, return null string
	if (cart == null) return "";
		
	// parse out the details for the specified itemId
	var p = new Parser(cart);
	var itemDetails = p.extract("{itmid=" + itemId + ";", "}");
	
	// return the itemDetails
	return itemDetails;

}

/**
 * Creates a delimitted string containing the specified information and returns it.
 */
function createItemDetails(itemId, type, quantity, price, description) {
	var itemDetails = "{" + 
	                   "itmid=" + itemId + ";" +
	                   "type=" + type + ";" +
					   "qnty=" + quantity + ";" +
					   "price=" + price + ";" +
					   "desc=" + description + ";" +
					   "}";
	return itemDetails;
}

/**
 * The getExpires function returns an expiration date based on a specified number of 
 * days from the current day.
 */
function getExpires(days) {
	var today = new Date();
	var expires = new Date(today.getTime() + (days * 86400000));
	return expires;
}

/**
 * The Get_Cookie function returns an unescaped value for the specified cookie
 * name.  Returns null if a value for the specified name cannot be found.
 */
function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

/**
 * The Set_Cookie function sets a cookie with the specified name and value.  The
 * expiration date, path, domain, and security can also be specified.  The value
 * will be escaped, so it will need to be unescaped when it is read back.
 */
function Set_Cookie(name,value,expires,path,domain,secure) {
	if (null == path || path == '' || strlen(path) == 0) {
		path = '/';
	}

    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

/**
 * The Delete_Cookie function removes the cookie with the specified name, path,
 * and domain from the current client browser.
 */
function Delete_Cookie(name,path,domain) {
	if (null == path || path == '' || strlen(path) == 0) {
		path = '/';
	}
  if (Get_Cookie(name))
    document.cookie =
      name + '=' +
      ( (path) ? ';path=' + path : '') +
      ( (domain) ? ';domain=' + domain : '') +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
