Cart = function() {
  var products = {}, cart = [];
  function updateCart() {
    if (document.getElementById('cart_details')) {
      var contents = '<p class="center">&mdash; Empty &mdash;</p>', ttl_shipping = 0, ttl_cart = 0, opt_idx = 0, ttl_weight = 0;
      for (var i in cart) {
        if (contents == '<p class="center">&mdash; Empty &mdash;</p>') {
          contents = '<table cellspacing="0" class="cart_table"><tr><th></th><th>Qty</th><th>Prod</th><th>Base&nbsp;Price</th></tr>';
        }
        contents += '<tr><td><button onclick="Cart.removeProduct(' + i + ');" class="product_remove"><img src="/images/del.png" alt="x"></button></td><td>' + cart[i]['quantity']
                  + '</td><td title="' + products[cart[i]['model']]['name'] + '"><a href="http://www.cherishscountrystore.com/product/' + products[cart[i]['model']]['id'] + '">' + products[cart[i]['model']]['name'].toMaxLen(15)
                  + '</a></td><td class="cell_currency">' + (Math.round(products[cart[i]['model']]['base_price']*100,1)/100).format('$###,###[.]##')
                  + '</td></tr>';
        ttl_weight += cart[i]['quantity'] * products[cart[i]['model']]['weight'];
        ttl_shipping += cart[i]['quantity'] * cart[i]['shipping_cost'];
        ttl_cart += cart[i]['quantity'] * products[cart[i]['model']]['base_price'];
        //Add option prices
        while (cart[i]['option_' + opt_idx]) {
          switch (products[cart[i]['model']]['options'][opt_idx]['type']) {
            case 'Text':
              ttl_shipping += parseFloat(products[cart[i]['model']]['options'][opt_idx]['base_shipping']);
              ttl_cart += parseFloat(products[cart[i]['model']]['options'][opt_idx]['base_charge']) + cart[i]['option_' + opt_idx].length * parseFloat(products[cart[i]['model']]['options'][opt_idx]['charge_per_letter']);
              break;
            case 'Choices':
              ttl_shipping += parseFloat(products[cart[i]['model']]['options'][opt_idx]['base_shipping']) + parseFloat(products[cart[i]['model']]['options'][opt_idx]['choices'][cart[i]['option_' + opt_idx]]['shipping']);;
              ttl_cart += parseFloat(products[cart[i]['model']]['options'][opt_idx]['base_charge']) + parseFloat(products[cart[i]['model']]['options'][opt_idx]['choices'][cart[i]['option_' + opt_idx]]['charge']);
              break;  
          }
          opt_idx++;
        }
        opt_idx =0;
      }
      ttl_weight += 0.5; //Force Ceiling function for shipping
      ttl_weight = Math.round(ttl_weight);
      switch (ttl_weight) {
        case 1:
          ttl_shipping += 5.45;
          break;
        case 2:
          ttl_shipping += 8.6;
          break;
        case 3:
          ttl_shipping += 10.35;
          break;
        case 4:
          ttl_shipping += 13.5;
          break;
        case 5:
          ttl_shipping += 15.45;
          break;
        case 6:
          ttl_shipping += 17.3;
          break;
        case 7:
          ttl_shipping += 19.15;
          break;
        case 8:
          ttl_shipping += 21;
          break;
        case 9:
          ttl_shipping += 22.9;
          break;
        case 10:
          ttl_shipping += 24.7;
          break;
        case 11:
          ttl_shipping += 26.55;
          break;
        case 12:
          ttl_shipping += 28.85;
          break;
        case 13:
          ttl_shipping += 30.95;
          break;
        case 14:
          ttl_shipping += 32.65;
          break;
        case 15:
          ttl_shipping += 34.1;
          break;
        case 16:
          ttl_shipping += 36;
          break;
        case 17:
          ttl_shipping += 37.85;
          break;
        case 18:
          ttl_shipping += 39.8;
          break;
        case 19:
          ttl_shipping += 41.65;
          break;  
        case 20:
          ttl_shipping +=  42.7;
          break;
        case 21:
          ttl_shipping +=  43.35;
          break;
        case 22:
          ttl_shipping +=  44.35;
          break;
        case 23:
          ttl_shipping +=  45.15;
          break;
        case 24:
          ttl_shipping +=  46.05;
          break;
        case 25:
          ttl_shipping +=  46.75;
          break;
        case 26:
          ttl_shipping +=  47.85;
          break;
        case 27:
          ttl_shipping +=  48.5;
          break;
        case 28:
          ttl_shipping +=  49.2;
          break;
        case 29:
          ttl_shipping +=  50;
          break;
        case 30:
          ttl_shipping +=  51.4;
          break;
        case 31:
          ttl_shipping +=  52.15;
          break;
        case 32:
          ttl_shipping +=  52.85;
          break;
        case 33:
          ttl_shipping +=  53.55;
          break;
        case 34:
          ttl_shipping +=  55.1;
          break;
        case 35:
          ttl_shipping +=  56.6;
          break;
        case 36:
          ttl_shipping +=  58.05;
          break;
        case 37:
          ttl_shipping +=  59.5;
          break;
        case 38:
          ttl_shipping +=  61.2;
          break;
        case 39:
          ttl_shipping +=  62.65;
          break;
        case 40:
          ttl_shipping +=  63.65;
          break;
        case 41:
          ttl_shipping +=  64.70 ;
          break;
        case 42:
          ttl_shipping +=  65.85;
          break;
        case 43:
          ttl_shipping +=  67.45;
          break;
        case 44:
          ttl_shipping +=  68.55;
          break;
        case 45:
          ttl_shipping +=  69.3;
          break;
        case 46:
          ttl_shipping +=  70.05;
          break;
        case 47:
          ttl_shipping +=  70.75;
          break;
        case 48:
          ttl_shipping +=  71.7;
          break;
        case 49:
          ttl_shipping +=  72.65;
          break;
        case 50:
          ttl_shipping +=  73.65;
          break;
        case 51:
          ttl_shipping +=  74.65;
          break;
        case 52:
          ttl_shipping +=  75.45;
          break;
        case 53:
          ttl_shipping +=  76.05;
          break;
        case 54:
          ttl_shipping +=  76.65;
          break;
        case 55:
          ttl_shipping +=  77.2;
          break;
        case 56:
          ttl_shipping +=  77.75;
          break;
        case 57:
          ttl_shipping +=  78.3;
          break;
        case 58:
          ttl_shipping +=  78.75;
          break;
        case 59:
          ttl_shipping +=  79.25;
          break;
        case 60:
          ttl_shipping +=  79.65;
          break;
        case 61:
          ttl_shipping +=  80.1;
          break;
        case 62:
          ttl_shipping +=  80.5;
          break;
        case 63:
          ttl_shipping +=  80.9;
          break;
        case 64:
          ttl_shipping +=  81.25;
          break;
        case 65:
          ttl_shipping +=  81.55;
          break;
        case 66:
          ttl_shipping +=  81.9;
          break;
        case 67:
          ttl_shipping +=  82.2;
          break;
        case 68:
          ttl_shipping +=  82.45;
          break;
        case 69:
          ttl_shipping +=  82.7;
          break;
        default:
          ttl_shipping +=  82.9;
          break;
      }
      
      if (contents != '<p class="center">&mdash; Empty &mdash;</p>') {
        contents += '<tr class="cart_summary_row"><td colspan="3">Est. Shipping</td><td class="cell_currency">' + (Math.round(100*ttl_shipping,1)/100).format('$###,###[.]##') + '</td></tr>'
                  + '<tr class="cart_summary_row"><td colspan="3">Est. Grand Total</td><td class="cell_currency">' + (Math.round(100 * (ttl_cart + ttl_shipping),1)/100).format('$###,###[.]##') + '</td></tr>'
                  + '</table><p class="center nomargin"><a href="/index.php?page=checkout" class="checkout_link">Checkout</a></p>';

        CookieManager.create('total_cost', Math.round(100 * (ttl_cart + ttl_shipping),1)/100);
      }
      document.getElementById('cart_details').innerHTML = contents;
    }
    if (document.getElementById('checkout-cart')) {
      contents = '<ul>';
      for (var i in cart) {
        contents += '<li>' + cart[i]['quantity'] + ' ' + products[cart[i]['model']]['name'];
        if (cart[i]['option_' + opt_idx]) {
          contents += '<ul>';
        }
        while (cart[i]['option_' + opt_idx]) {
          switch (products[cart[i]['model']]['options'][opt_idx]['type']) {
            case 'Text':
              contents += '<li><label>' + products[cart[i]['model']]['options'][opt_idx]['label'] + ': </label>' + cart[i]['option_' + opt_idx] + '</li>';
              break;
            case 'Choices':
              contents += '<li><label>' + products[cart[i]['model']]['options'][opt_idx]['label'] + ': </label>' + products[cart[i]['model']]['options'][opt_idx]['choices'][cart[i]['option_' + opt_idx]]['name'] + '</li>';
              break;
          }          
          opt_idx++;
        }
        if (cart[i]['option_' + opt_idx]) {
          contents += '<ul>';
        }
        contents += '</li>';
        opt_idx =0;
      }
      contents += '</ul>';
      contents += '<strong>Estimated Shipping:</strong> ' + (Math.round(100* ttl_shipping)/100).format('$###,###[.]##') + '<br>';
      contents += '<strong>Estimated Total:</strong> ' + (Math.round(100 * (ttl_cart + ttl_shipping))/100).format('$###,###[.]##') + '<br>';
      var checkout_details = contents;
      //contents += '<p>Complete the form below to authorize, but not charge, your card for $' + (ttl_cart + ttl_shipping) + '.  Your card will be charged after your order is created.';
      contents += '<form method="POST" action="index.php?page=pay">';
      contents += '<textarea name="order_details" style="display:none;">';
      contents += checkout_details;
      contents += '</textarea>';
      contents += '<center><input type="submit" value="My Order Is Correct &mdash; I\'m ready to pay&hellip;"></center>';
      contents += '</form>';
      document.getElementById('checkout-cart').innerHTML = '<h2>Your Order</h2>' + contents;
    }
  }
  function toTable() {
  }
  function removeProduct(idx) {
    if (cart[idx]) {
      cart.splice(idx,1);
      saveCart();
      updateCart();
    }
  }
  function addProduct(model) {
    var cart_item = {
      'model': model,
      'quantity': Math.min( parseInt(document.getElementById('product_' + model + '_qty').value), products[model]['stock']),
      'shipping_cost': document.getElementById('product_' + model + '_shipping').value
    };
    //TODO Confirm cart updated
    var idx = 0;
    while (document.getElementById('option_' + idx)) {
      if (document.getElementById('option_' + idx).tagName.toLowerCase() == 'select') {
        cart_item['option_' + idx] = document.getElementById('option_' + idx).options[document.getElementById('option_' + idx).options.selectedIndex].value;
      } else if (document.getElementById('option_' + idx).tagName.toLowerCase() == 'input') {
        cart_item['option_' + idx] = document.getElementById('option_' + idx).value;
      }
      idx++;
    }
    cart.push(cart_item);
    //Remove added item from stock
    products[model]['stock'] -= cart[cart.length - 1]['quantity'];
    saveCart();
    updateCart();
  }
  function registerProduct(pid, model, nme, base_price, est_shipping, stock, weight, options) {
    products[model] = {
      'id': pid,
      'name': nme,
      'base_price': base_price,
      'est_shipping': est_shipping,
      'stock': stock,
      'weight': weight,
      'options': []
    }
    if (options && options.length > 0) {
      products[model].options = options.split('`');
      var option_arr = [], choice_arr = [];
      for (var i=0;i<products[model].options.length;i++) {
        option_arr = products[model].options[i].split('~');
        products[model].options[i] = {};
        products[model].options[i].label = option_arr[0];
        products[model].options[i].base_charge = option_arr[1];
        products[model].options[i].base_shipping = option_arr[2];
        products[model].options[i].type = option_arr[3];
        products[model].options[i].charge_per_letter = option_arr[4];
        products[model].options[i].choices = []; 
        if (products[model].options[i].type == 'Choices') {
          option_arr = option_arr[5].split(',');
          for (var j=0;j<option_arr.length;j++) {
            choice_arr = option_arr[j].split('^');
            products[model].options[i].choices.push({
              'name': choice_arr[0],
              'charge': choice_arr[1],
              'shipping': choice_arr[2]
            });
          }
        }
      }
    }
  }
  function saveCart() {
    var cart_string = JSON.stringify(cart);
    if (window.localStorage) {
      window.localStorage['cart'] = cart_string;
    }
  }
  function restoreCart() {
    if (window.localStorage && window.localStorage['cart']) {
      cart = JSON.parse(window.localStorage['cart']);
    }
  }

  return {
    'init': function() { restoreCart(); updateCart()},
    'update': updateCart,
    'addProduct': addProduct,
    'removeProduct': removeProduct,
    'registerProduct': registerProduct
  };
}();
onLoadCalls.push(new onLoadCall('Cart.init',''));
