/**
 * @author thomas
 */
var ShoppingCart = new Class({
	Implements: [Options, Events],
	
	options: {
		'storeName': 'sevenspire-sc',
		'items': null,
		'cookieOpts': {},
		'maxAmount': -1,
		'shippingPrice': 0
		/*
		 'onSave':
		 */
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		var klass = this;
		
		this.options.items = $$(this.options.items).addEvent('click', function(e){
			e.stop();
			klass.addItem(this.get('rel'));
		});
		
		this.initStore();
		
		this.fireEvent('save');
	},
	
	initStore: function(){
		var cookie = $H(JSON.decode(Cookie.read(this.options.storeName)) || {'items': {}, 'shippingPrice': this.options.shippingPrice});
		this.store = $H(cookie.get('items'));
		this.shippingPrice = cookie.get('shippingPrice');
	},
	
	addItem: function(id, amount){
		amount = $pick(amount, 1);
		
		var item = this.store.get(id);
		
		if(item){
			item = item.toInt() + amount.toInt();
		}
		else{
			item = amount;
		}
		
		if (this.options.maxAmount > 0) {
			item = item.min(this.options.maxAmount);
		}
		
		this.store.set(id, item);
		this.fireEvent('addItem', [id, amount, item]);
		this.save();
		
		return this;
	},
	
	removeItem: function(id, amount){
		var item = this.store.get(id);
		var total = 0;

		if(item && amount && item.toInt() > amount.toInt()){
			item = item.toInt() - amount.toInt();
			total = item;
			this.store.set(id, item);
			this.save();
			return this;
		}
		
		this.store.erase(id);
		this.fireEvent('removeItem', [id, amount, total]);
		this.save();
		return this;
	},
	
	setItem: function(id, amount){
		if (this.options.maxAmount > 0) {
			amount = amount.toInt().min(this.options.maxAmount);
		}
		
		this.store.set(id, amount);
		this.fireEvent('setItem', [id, amount]);
		this.save();
		return this;
	},
	
	setShippingPrice: function(amount){
		this.shippingPrice = amount;
		this.fireEvent('setShippingPrice', [amount]);
		this.save();
		return this;
	},
	
	empty: function(){
		this.store.empty();
		this.save();
		this.fireEvent('empty');
		return this;
	},
	
	save: function(){
		var cookie = {'shippingPrice': this.shippingPrice, 'items': this.store.getClean()};
		Cookie.write(this.options.storeName, JSON.encode(cookie), this.options.cookieOpts);
		this.fireEvent('save');
		return this;
	}
});

