/**
 * 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
 *
 * REQUIRES: ProcessAccessoryClntAPIs.js
 */

// The name of the cookie used to store the shopping cart information
var cartCookieName = "sunsetterAwningCart";

// The number of days to store the shopping cart information in the user's browser
var cartCookieExpiration = 30;

/**------------ PUBLIC APIS --------------------------------------------------------*/

/**
 * This method will return true if there is an awning in the cart,
 * otherwise it will return false.  
 */
  function isAwningInCart(){
  // If the customer has been through step3 then we have an awning on
  // the order.  
    var hasAwningOnOrder=false;
    if (getItemValue("step3") == "true") {
      hasAwningOnOrder=true;
    }
    
    return hasAwningOnOrder;
  }

  /** 
   * This method will determine if an incomplete awning is in the cart.
   */
  function isIncompleteAwningInCart() {
  
    var incomplete = false;
    if (getItemValue("step1") == "true" &&
        (getItemValue("step4") == "false" || 
         getItemValue("step4") == "")) {
        incomplete = true;
    }
    
    return incomplete;
  }
 
/**
 * This method will remove the entries in the shopping that
 * make up an awning.  With these removed an awning will no
 * nolonger be in the cart.
 */
function removeAwning() {
  
    removeItem("model");
    removeItem("xmodel");
    removeItem("size");
    removeItem("xsize");
    removeItem("color");
    removeItem("side");
	removeItem("sideselected");
    removeItem("bracket");
	removeItem("bracketselected");
    removeItem("step1");
    removeItem("step2");
    removeItem("step3");
    removeItem("step3a");
    removeItem("step4");
    removeItem("step5a");
    removeItem("step6");
    removeItem("masonry"); 
	removeItem("masonryselected");
    removeItem("InitCheck")  //Renji
	removeItem('combow');
	removeItem('aww');
  	removeItem("raftbrack");
	removeItem("rafter"); 
    removeItem("rafterselected"); 

    // Remove any free items, or awning accessories    
    var itms = getItems();
	  if (itms != null) {
    
      // Look for free items to remove.
		  for (var i = 0; i < itms.length; i++) {
  			var itm = itms[i];
        if (itm["type"] == "FreeItem" || 
            itm["type"] == "FreePackage" ||
            itm["type"] == "AwningPackage" ||
            itm["type"] == "AwningItem") {
          removeItem(itm["itemid"]);
        }
      }
    }    
}

/**
 * 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=", ";"),
            "value" : p2.extract("value=", ";") };
		}
		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 to get the value for the specific item id.  Returns a
 * null string ("") if the specified item id does not exist.
 */
function getItemValue(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("value=", ";");
	
}

/**
 *
 * This method is a short cut to just add and item specifing just a value.
 */
function addItemValue(itemId, type, value){
  
  // Simply default all the other args to "".
  addItem(itemId, type, "", "", "", value, "REPLACE");
  
}
  
/**
 * The itemId is intended to be a unique identifier for a specific item. The itemId must be 
 * be unique for each item addded to the cart, otherwise the action param is used to determine
 * the action taken by this method. 
 *  action = null or "NOACTION" then false is returned is the item exists in the cart.
 *  action = "REPLACE" then replace the entry in the cart with the specified data. returns true
 *  action = "UPDATEQTY" then update the qty in the cart for this item. returns true
 * Returns true if the item is successfully added.
 */
function addItem(itemId, type, quantity, price, description, value, action) {

	// get the value in the sunsetter cart cookie
	var cart = Get_Cookie(cartCookieName);
	if (cart == null) cart = "";
	
	// get the info for the specified item id. 
	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);

  // If the item exists then process according to the action parameter.	
	if (itemDetails != "") {
    // If action is null, or NOACTION then just return false.
    if ((action == null) || (action == "NOACTION")) {
      // We return here so the cookie is not changed and the item
      // will still be there the next time.
      return false;
    }
    
    // If action == UPDATEQTY then update the sum by adding the new
    // quantity to the existing.
    if (action == "UPDATEQTY") {
      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, value);
    }
    else {
      // If action is replace then replace this entry with the new
      // entry info.
      cart = p.text;
	    cart += createItemDetails(itemId, type, quantity, price, description, value);
    }
  }
  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, value);
  }
    
	// 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);
  if (cart == null)
    return true;
    
	// 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 method will remove the entries in the shopping that
 * that are the same type.
 */
function removeItemsByType(type) {
  
    // Remove any free items, or awning accessories    
    var itms = getItems();
	  if (itms != null) {
    
      	// Look for items to remove.
		for (var i = 0; i < itms.length; i++) {
  			var itm = itms[i];
        	if (itm["type"] == type) {
          		removeItem(itm["itemid"]);
        	}
      	}
    }    
}


/**
 * 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, value) {
	var itemDetails = "{" + 
	                   "itmid=" + itemId + ";" +
	                   "type=" + type + ";" +
					   "qnty=" + quantity + ";" +
					   "price=" + price + ";" +
					   "desc=" + description + ";" +
             "value=" + value + ";" +
					   "}";
	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) {
    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 (Get_Cookie(name))
    document.cookie =
      name + '=' +
      ( (path) ? ';path=' + path : ''); +
      ( (domain) ? ';domain=' + domain : '') +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

