var Cart = {
	cart : Array(),
	init : function() {
		if ($.cookie('cart')) {
			this.cart = JSON.parse($.cookie('cart'));
		}
	},
	add : function(id, title, count, price) {
		this.init();
		var good = this.find(id);
		if (good !== false) {
			this.remove(id);
		}
		if (id && count && price && count>0 && price>=0) {
			this.cart.push({'id': id, 'count': Math.round(count*10000)/10000, 'price': price});
		}

		$.cookie('cart', JSON.stringify(this.cart), {path: '/', expires: 14});
		this.afterFunc();
	},
	setCount : function(id, count) {
		this.init();
		var good = this.find(id);
		if (good !== false) {
			this.cart[good].count = count;
			$.cookie('cart', JSON.stringify(this.cart), {path: '/', expires: 14});
			this.afterFunc();
			return true;
		}
		else {
			return false;
		}
	},
	giveMeMore : function(id, title, count, price) {
		this.init();
		var good = this.find(id);
		if (good !== false) {
			this.setCount(id, Math.round((count*1 + this.cart[good].count*1)*10000)/10000);
		}
		else {
			this.add(id, title, count, price);
		}
	},
	remove : function(id) {
		this.init();
		for ( var good in this.cart) {
			if (this.cart[good].id == id) {
				this.cart.splice(good, 1);
			}
		}
		$.cookie('cart', JSON.stringify(this.cart), {path: '/', expires: 14});
		this.afterFunc();
    return true;
	},
  removeAll: function(){
    this.cart = Array();
    $.cookie('cart', JSON.stringify(this.cart), {path: '/', expires: 14});
    this.afterFunc();
  },
	find : function(id) {
		this.init();
		for (var good in this.cart) {
			if (this.cart[good].id == id) {
				return good;
			}
		}
		return false;
	},
	get : function(id) {
		return this.cart[this.find(id)];
	},
	afterFunc : function() {
		this.init();
		if (Cart.cart.length > 0) {
      var totalsomme = 0;
      var totalcount = 0
      for(i in this.cart){
        totalsomme += this.cart[i]['count']*this.cart[i]['price'];
        totalcount += parseInt(this.cart[i]['count']);
        }
        
      if(0 == totalcount)totalsomme = 0;  
        
       $('#cart-somme').html(totalsomme);
       $('#cart-somme-2').html(totalsomme);
     
			if (5 <= totalcount &&  totalcount <= 20) {
				$('#cart-count').html(totalcount+' товаров');
        $('#totalcartsomme').show();
			} else {
				var count = totalcount.toString();
				if (count[count.length-1] == 1) {
					$('#cart-count').html(totalcount+' товар');
				} else if (2 <= totalcount && totalcount <= 4) {
					$('#cart-count').html(totalcount+' товара');
				} else {
					$('#cart-count').html(totalcount+' товаров');
				}
        $('#totalcartsomme').show();
			}
		} else {
			$('#cart-count').html('нет товаров');
			$('#totalcartsomme').hide();
			$('.cartisempty').hide();
			$('#cartisempty2').hide();
			$('.cartemptytext').show();
		}
	}
};
$(document).ready(function(){Cart.afterFunc();});
