Event.observe(window, 'load', function(){
  Cart.loadData();
  if (Cart.dataStore && typeof Cart.dataStore.length == 'undefined'){
    Cart.Block.show();
  }
});

Cart = {
  dataStore: {},
  loaded: false
};

Cart.Block = {
  options: {
    holderId: 'cartBlockHolder',
    itemsHolderId: 'cartBlockItems',
    itemClassName: 'cartBlockItem',
    itemTemplate: new Template(
      '<tr><td class="cartItemName"><a href="#{url}">#{name}</a></td><td class="cartItemPrice"> #{price}</td> <td class="cartItemQuantity"> Х #{quantity}</td> <td class="cartItemTotal"> = #{sum}</td></tr>'
      ),
    totalId: 'cartBlockTotal',
    totalTemplate: new Template(
      'Общая сумма:<br /> <span> #{total} </span>'
      ),
    highlight:{
      startColor: '#B74D26',
      endColor: '#FFFFFF',
      restoreColor: '#FFDCB4'
    }
  }
};

Cart.Module = {
  options: {
    holderId: 'cartHolder',
    tableId: 'cartTable',
    rowIdBegin: 'cartRow_',
    totalId: 'cartTotal',
    itemSumColumnNumber: 3,
    cartEmptyMessageId: 'cartEmptyMessage'
  }
};


Cart.loadData = function(){
  if (Cart.loaded == false){
    new Ajax.Request('/cart/list', {
      method: 'get',
      asynchronous: false,
      onSuccess: function(transport){
        Cart.dataStore = transport.responseText.evalJSON(true);
        Cart.loaded = true;
      }
    });
  }
};

Cart.add = function(item, callback){
  var id = parseInt(item.id) || null;
  var context = item.context || null;
  var quantity = parseInt(item.quantity) || null;
  var url = item.url || null;
  if (id && context && quantity) {
    new Ajax.Request('/cart/add', {
      method: 'post',
      parameters: {
        id: id,
        context: context,
        quantity: quantity,
        url: url
      },
      onSuccess: callback
    });
  }
};

Cart.changeQuantity = function (item, callback){
  new Ajax.Request('/cart/changequantity', {
    method: 'post',
    parameters: item,
    onSuccess: callback
  });
}

Cart.remove = function(item, callback){
  new Ajax.Request('/cart/remove', {
    method: 'post',
    parameters: item,
    onSuccess: callback
  });
}

Cart.countTotalSum = function(){
  var total = 0;
  for (var context in Cart.dataStore) {
    for (var i in Cart.dataStore[context]) {
      var item = Cart.dataStore[context][i];
      var sum = Common.isDealer ? parseFloat(item.price * item.quantity) : Math.round(item.price * Common.currencyRate) * item.quantity;
      total += sum;
    }
  }
  return total;
}

Cart.clear = function(callback){
  new Ajax.Request('/cart/clear', {
    method: 'get',
    onSuccess: callback
  });
}

Cart.Module.showEmptyMessage = function(){
  $(Cart.Module.options.holderId).hide();
  $(Cart.Module.options.cartEmptyMessageId).show();
}



Cart.Block.show = function(){
  if (!$(Cart.Block.options.holderId)){
    return;
  }
  $(Cart.Block.options.holderId).show();
  var holder = $(Cart.Block.options.itemsHolderId);
  holder.update('');
    
  var total = 0;
  for (context in Cart.dataStore) {
    for (i in Cart.dataStore[context]) {
      var item = Cart.dataStore[context][i];

      item.url = item.url ? item.url : '#';

      item.price = Common.isDealer ? item.price : Math.round(item.price * Common.currencyRate);
      var sum = parseFloat(item.price * item.quantity);

      item.sum = Common.priceTemplate.evaluate({
        value: price_format(sum)
      });
      item.price = Common.priceTemplate.evaluate({
        value: price_format(item.price)
      });
      total += sum;

      var text = Cart.Block.options.itemTemplate.evaluate(item);
      holder.insert(text, holder);
    }
  }
    
  $(Cart.Block.options.totalId).innerHTML = Cart.Block.options.totalTemplate.evaluate({
    total: Common.priceTemplate.evaluate({
      value: price_format(total)
    })
  });
}

Cart.Block.add = function(item){
  var callback = function(transport){
    Cart.dataStore = transport.responseText.evalJSON(true);
    Cart.Block.show();
    new Effect.Highlight($(Cart.Block.options.holderId), {
      startcolor: Cart.Block.options.highlight.startColor,
      endcolor: Cart.Block.options.highlight.endColor,
      restorecolor: Cart.Block.options.highlight.restoreColor
    });
  }
	
  Cart.add(item, callback);
}

Cart.Module.changeQuantity = function (item){
  var id = parseInt(item.id) || null;
  var context = item.context || null;
  var price = parseFloat(item.price) || null;
  var quantity = parseInt(item.quantity) || null;
    
  var callback = function(transport){
    Cart.dataStore = transport.responseText.evalJSON(true);
    var sum = Common.isDealer ? price * quantity : price * quantity * Common.currencyRate;
    var cells = $(Cart.Module.options.rowIdBegin + id).getElementsByTagName('td');
    cells[Cart.Module.options.itemSumColumnNumber].innerHTML = Common.priceTemplate.evaluate({
      value: price_format(sum)
    });
    Cart.Module.countTotalSum();
  }
  Cart.changeQuantity({
    id: id,
    context: context,
    quantity: quantity
  },
  callback
  );
}

Cart.Module.remove = function(item){
  var id = parseInt(item.id);
  var callback = function(transport){
    Cart.dataStore = transport.responseText.evalJSON(true);
    if (Cart.dataStore.length || Cart.dataStore.length < 1){
      Cart.Module.showEmptyMessage();
      return;
    }
    if ($('cartRow_' + id)){
      $('cartRow_' + id).remove();
    }
    Cart.Module.countTotalSum();
  }
  Cart.remove(item, callback);
}

Cart.Module.countTotalSum = function(){
  var sum = price_format(Cart.countTotalSum());
  $(Cart.Module.options.totalId).innerHTML = Common.priceTemplate.evaluate({
    value: sum
  });
}

Cart.Module.clear = function(){
  var callback = function(){
    Cart.Module.showEmptyMessage();
  }
  Cart.clear(callback);
}
