if(typeof(window.console) == 'undefined') window.console = {};
if(typeof(window.console.log) == 'undefined') window.console.log = 
function() {};

var ShopCart = function() {
  var _cookies = { items : "shopItems", prices : "shopPrices", quantities 
: "shopQuantities", titles : "shopTitles" };
  var _removeCookie = function(name, pos) {
    console.log("RemoveCookie", name, pos, this);
    var cookie = readCookie(name);
    var items = cookie.split('_');
    items.splice(pos, 1);
    createCookie(name, items.join('_'), 0);
  }
  var _updateCookie = function(name, value, config) {
      console.log(name, value, pos, this);
      var cookie = readCookie(name);
      if(cookie == null || cookie == "") {
        createCookie(name, value, 0);
      } else {
       var items = cookie.split('_');
       var pos = ((config && config.pos != null) ? config.pos : 
items.length);
       if(config && config.method == "sum")
         items[pos] = parseInt(items[pos]) + parseInt(value);
       else
         items[pos] = value;
       createCookie(name, items.join('_'), 0);
      }
  }
  function _findItemIdx(itemID) {
    var itemCookie = readCookie(_cookies.items) || "";
    var itemIDs = itemCookie.split('_');  
    var found = -1;
    for(var i = 0; i < itemIDs.length && found == -1; i++)
    {
      if(itemIDs[i] == itemID)
         found = i;
    }
    return found;
  }

  return {
    formName: "shopping_cart_form",
    Add: function(id, form) {
      console.log('Add', id, form, this);

      var found = _findItemIdx(id);
      if(found != -1) {
        _updateCookie(_cookies.prices, form.price.value, { pos: found });
        _updateCookie(_cookies.titles, form.title.value, { pos : found });
        _updateCookie(_cookies.quantities, form.quantity.value, { pos : 
found, method : 'sum' });
      } else {
        _updateCookie(_cookies.items, id);
        _updateCookie(_cookies.prices, form.price.value);
        _updateCookie(_cookies.titles, form.title.value);
        _updateCookie(_cookies.quantities, form.quantity.value);
      }
      document.location.reload();
      return false;
    },
    Update: function(fieldName, cookieIdx) {
      var quantity = 
document.getElementById(this.formName)[fieldName].value;
      if(quantity > 0)
        _updateCookie(_cookies.quantities, quantity, { pos : cookieIdx });
      else
        this.Remove(cookieIdx);
    },
    Remove: function(cookieIdx) {
      _removeCookie(_cookies.items, cookieIdx);
      _removeCookie(_cookies.quantities, cookieIdx);
      _removeCookie(_cookies.titles, cookieIdx);
      _removeCookie(_cookies.prices, cookieIdx);
    },
    Clear: function() {
      eraseCookie(_cookies.items);
      eraseCookie(_cookies.quantities);
      eraseCookie(_cookies.titles);
      eraseCookie(_cookies.prices);
    }
  };

}();
