var CocoaNymphCart = new Class({

  options: {
  
  },
  
  styles: {
    cartTitleStyle: {
      width: '94%',
      borderBottom: '2px solid #98677E',
      paddingBottom: '4px',
      marginBottom: '8px',
      marginLeft: 'auto',
      marginRight: 'auto',
      textAlign: 'left'
    },
    headerDivStyle: {
      cursor: 'pointer'
    },
    headerTableStyle: {
      width: '94%',
      marginRight: 'auto',
      marginLeft: 'auto'
    },
    descTdStyle: {
      fontWeight: 'bold',
      textAlign: 'left'
    },
    priceTdStyle: {
      textAlign: 'right'
    },
    boxContainerDivStyle: {
    },
    addBoxStyle: {
      cssFloat: 'right',
      fontSize: '13px',
      cursor: 'pointer'
    },
    totalTableStyle: {
      color: '#4E1F3E',
      width: '94%',
      marginTop: '16px',
      borderTop: '2px solid #98677E',
      marginRight: 'auto',
      marginLeft: 'auto'
    },
    recalcTdStyle: {
      verticalAlign: 'top'
    },
    totalTdStyle: {
      verticalAlign: 'top',
      textAlign: 'right'
    },
    checkoutButtonStyle: {
      cursor: 'pointer',
      marginTop: '6px'
    }
  },

	initialize: function(container)
	{
    this.container = $(container);
    this.boxes = [];
    
    var cookie = Cookie.get('cart');
    try { if (cookie) this.loadFromCookie(cookie); }
    catch(e) { }
    
    this.render();
  },
  
  loadFromCookie: function(cookie)
  {
    this.boxes = [];
    var persistentData = $A(Json.evaluate(cookie));
    persistentData.each(function(item){
      if (item.size)
      {
        this.boxes.push(new Box(item.size, item.chocolates)); // box
      }
      else
      {
        this.boxes.push(new Confection(item.code, item.src)); // confection
      }
    }.bind(this));
    
    if (this.boxes.length > 0) this.currentBox = this.boxes[0];
  },
  
  saveToCookie: function()
  {
    var persistentData = [];
    this.boxes.each(function(box) {
      persistentData.push(box.persistentData());
    });
    
    Cookie.set('cart', Json.toString(persistentData), {duration: 730});
  },
  
  render: function()
  {
    this.saveToCookie();
    this.container.innerHTML = '';
    
    this.headers = [];
    this.boxContainers = [];
    
    if (this.boxes.length > 0)
    {
      var cartTitleDiv = createElement('div').setStyles(this.styles.cartTitleStyle);
      var titleSpan = createElement('span').setStyles({cssFloat: 'left'});
      titleSpan.innerHTML = 'Shopping Cart';
      var addBoxSpan = createElement('span').setStyles(this.styles.addBoxStyle);
      addBoxSpan.innerHTML = '&nbsp; &nbsp; &nbsp; <img src="images/add_icon.gif" style="position: relative; top: 3px;"> add another box';
      addBoxSpan.onmousedown = this.showBoxSizeChoices.bind(this);
      
      var clearDiv = createElement('div').setStyles({clear: 'both'});
      
      cartTitleDiv.appendChild(titleSpan);
      cartTitleDiv.appendChild(addBoxSpan);
      cartTitleDiv.appendChild(clearDiv);
      this.container.appendChild(cartTitleDiv);
    
      this.boxes.each(function(box) {
      
        var header = createElement('div').setStyles(this.styles.headerDivStyle);
        header.addClass('accordionHeader');
        header.box = box;
        
        var headerTable = createElement('table').setStyles(this.styles.headerTableStyle);
        var headerRow = $(headerTable.insertRow(-1));
        var descTd = $(headerRow.insertCell(-1)).setStyles(this.styles.descTdStyle);
        descTd.innerHTML = '<img src="' + box.getCartIcon() + '" style="position: relative; top: 1px;">'
          + ' <span style="position: relative; top: -10px;">' + box.getDescription() + '</span>';
        var priceTd = $(headerRow.insertCell(-1)).setStyles(this.styles.priceTdStyle);
        priceTd.innerHTML = this.formatCurrency(box.getPrice());
        
        header.appendChild(headerTable);
        this.headers.push(header);
        
        var boxContainer = createElement('div').setStyles(this.styles.boxContainerDivStyle);
        boxContainer.addClass('accordionContent');
        this.boxContainers.push(boxContainer);
        
        box.render(boxContainer);

        this.container.appendChild(header);
        this.container.appendChild(boxContainer);
      
      }.bind(this));
      this.addTotalTable();
      
      var currentBoxIndex = 0;
      if (this.currentBox) currentBoxIndex = this.boxes.indexOf(this.currentBox);
      
      this.accordion = new Accordion('div.accordionHeader', 'div.accordionContent', {
        opacity: true,
        display: currentBoxIndex,
        onActive: function(toggler, element){
          this.currentBox = toggler.box;
          toggler.firstChild.setStyle('color', '#4E1F3E');
        }.bind(this),
        onBackground: function(toggler, element){
          toggler.firstChild.setStyle('color', '#A0748A');
        }
      }, this.container);
    }
    else
    {
      this.menuHeaderImg = createElement('img');
      this.menuHeaderImg.src = 'images/menu_header.gif';
      this.menuHeaderImg.setStyles({cursor: 'pointer'});
      this.menuHeaderImg.onmousedown = this.showBoxSizeChoices.bind(this);
      this.container.appendChild(this.menuHeaderImg);
    }
  },
  
  addTotalTable: function()
  {
    this.totalTable = createElement('table').setStyles(this.styles.totalTableStyle);
    var tr = this.totalTable.insertRow(-1);

    var recalcTd = $(tr.insertCell(-1)).setStyles(this.styles.recalcTdStyle);
    recalcTd.innerHTML = '<br><div id="freeShippingDiv" style="width: 120px;"></div>';

    var totalTd = $(tr.insertCell(-1)).setStyles(this.styles.totalTdStyle);
    totalTd.innerHTML = 'Subtotal: &nbsp; CAD$ ' + this.formatCurrency(this.getTotal()) + '<br>';

    this.checkoutButton = createElement('img').setStyles(this.styles.checkoutButtonStyle);
    this.checkoutButton.src = 'images/checkout.gif';
    this.checkoutButton.onclick = function() {
      this.checkout();
    }.bind(this);
    
    totalTd.appendChild(this.checkoutButton);
    this.container.appendChild(this.totalTable);
    
    var total = this.getTotal();
    if (total >= 100)
    {
      $('freeShippingDiv').innerHTML = 'Your order qualifies for free shipping!';
    }
    else
    {
      var add = this.formatCurrency(100 - total);
      $('freeShippingDiv').innerHTML = 'Add ' + add + ' to your order and receive free shipping!';
    }
  },
  
  showBoxSizeChoices: function()
  {
    $('boxChooser').ShowDialog();
  },
  
  chooseBox: function(size)
  {
    $('boxChooser').HideDialog();
    
    var box = new Box(size);
    if (this.pendingChocolate)
    {
      box.addChocolate(this.pendingChocolate);
      this.pendingChocolate = false;
    }
    this.boxes.unshift(this.currentBox = box);
    this.render();
  },
  
  chooseChocolate: function(code)
  {
    if (!this.currentBox)
    {
      this.pendingChocolate = code;
      this.showBoxSizeChoices();
    }
    else if (!this.currentBox.addChocolate)
    {
      // currentBox is a confection.  Try to find a box with some room and if fail add a box
      for (var boxIndex = 0; boxIndex < this.boxes.length; boxIndex++)
      {
        var box = this.boxes[boxIndex];
        if (box.addChocolate && !box.isFull())
        {
          this.currentBox = box;
          this.currentBox.addChocolate(code);
          this.render();  // render the whole cart so we see the box open
          return;
        }
      }
      
      // no room in any of our boxes
      this.pendingChocolate = code;
      this.showBoxSizeChoices();
    }
    else
    {
      if (this.currentBox.isFull())
      {
        this.pendingChocolate = code;
        this.showBoxSizeChoices();
      }
      else
      {
        this.currentBox.addChocolate(code);
        this.currentBox.render();
        this.saveToCookie();
      }
    }
  },
  
  chooseConfection: function(code, src)
  {
    var confection = new Confection(code, src);
    this.boxes.unshift(confection);
    this.currentBox = confection;
    this.render();
  },
  
  removeBox: function(box)
  {
    if (confirm('Remove ' + box.getDescription() + ' from your order: are you sure?'))
    {
      this.boxes.splice(this.boxes.indexOf(box), 1);
      this.render();
    }
  },
  
  fillWithRandom: function()
  {
    this.boxes.each(function(box){
      if (box.fillWithRandom) box.fillWithRandom();
    });
  },
  
  checkout: function()
  {
    // first check to see if all the boxes are full
    for (var boxIndex = 0; boxIndex < this.boxes.length; boxIndex++)
    {
      var box = this.boxes[boxIndex];
      if (!box.isFull())
      {
        if (confirm('Some of your boxes are not yet full.  Would you like to fill them with random selections?'))
        {
          this.fillWithRandom();
          //this.render();
        }
        //return this.checkout();
      }
    }
    
    this.checkoutForm = $('checkoutForm');
    this.checkoutForm.innerHTML = '';
  
    this.insertFormField(this.checkoutForm, 'cmd', '_cart');
    this.insertFormField(this.checkoutForm, 'business', 'sales@cocoanymph.com');
    this.insertFormField(this.checkoutForm, 'currency_code', 'CAD');
    this.insertFormField(this.checkoutForm, 'upload', 1);
    this.insertFormField(this.checkoutForm, 'no_shipping', 2);
    this.insertFormField(this.checkoutForm, 'no_note', 1);
    this.insertFormField(this.checkoutForm, 'return', 'http://www.cocoanymph.com/thankyou.html');
    
    for (var i=0; i<this.boxes.length; i++)
    {
      var ordinal = i + 1;
      var box = this.boxes[i];
      var code = box.getProductCode();
    
      this.insertFormField(this.checkoutForm, 'amount_' + ordinal, box.getPrice());
      this.insertFormField(this.checkoutForm, 'item_name_' + ordinal, box.getDescription());
      this.insertFormField(this.checkoutForm, 'item_number_' + ordinal, code);
      this.insertFormField(this.checkoutForm, 'quantity_' + ordinal, 1);
    }
  
    this.checkoutForm.submit();
  },
  
  insertFormField: function(form, field, value)
  {
    var input = createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', field);
    input.value = value;
    form.appendChild(input);
    return input;
  },
  
  getTotal: function()
  {
    var total = 0;
    this.boxes.each(function(b){
      total += b.getPrice();
    }.bind(this));
    
    return total;
  },
  
  getTotalQuantity: function()
  {
    return this.boxes.length;
  },
  
  formatCurrency: function(c)
  {
    var s = c + '';
    
    var idx = s.indexOf('.');
    if (idx == -1) return s + '.00';
    
    var d = s.length - idx;
    if (d > 3) return s.substring(0, idx + 3);
    if (d == 2) return s + '0';
    if (d == 1) return s + '00';
    return s;
  },
  

  
  descriptions: {
    '1': 'The Liz',
    '7': 'Elphaba',
    '12': 'The Amy',
    '10': 'Lucy in the Chai',
    '4': 'Barnabas the Tortoise',
    '2': 'Fresh',
    '11': 'Chariot of Fire',
    '5': 'Octarine',
    '6': 'Glinda',
    '9': 'Illa (Fleur de Sel)',
    '8': 'Papillon (Raspberry)',
    '13': 'Melissa',
    '3': 'Coffee (Bean)',
    'S01': 'Mirth',
    'S02': 'Gingerbread',
    'S05': 'Candy Cane',
    'S03': 'Winter Whiskey',
    'S04': 'Pumpkin Caramel',
    'S06': 'Cranberry',
    'S07': 'Maple',
    'S08': 'Basque Square',
    'V01': 'Mischief',
    'V02': 'Desire',
    'V03': 'Blush',
    'V04': 'Luscious',
    'B01': 'Classic Dark Nymph',
    'B02': 'Twilight Nymph',
    'B03': 'Garden Nymph',
    'B04': 'Sea Nymph',
    'B05': 'Urban Nymph',
    'C01': 'English Toffee',
    'C02': 'Maple Pecans',
    'C03': 'Spiced Maple Pecans',
    'C04': 'Vanilla Marshmallows'
  }
});
	