var Cart = function(name, options) {
	this.name = name;
	if (options != undefined) {
		this.precision = options.presision || 2;
		this.expire = options.expire || 31;
		this.items = options.items || {};
		this.total = options.total || 0;
		this.quantity = options.quantity || 0;
		this.events = options.events || 0;
	} else {
		this.precision = 2;
		this.expire = 31;
		this.items = {};
		this.total = 0;
		this.quantity = 0;
		this.events;
	}
	this.add = function(id, price, quantity, force) {
		this.load(this.name);
		var obj = this;
		if (typeof this.items[id] == 'undefined') {
			this.items[id] = new CartItem();
			this.items[id].quantity = quantity;
			this.items[id].price = round_mod(price, this.precision);
			this.items[id].total = round_mod(quantity * price, this.precision);
			this.total += round_mod(this.items[id].total, this.precision);
			this.quantity += quantity;
		} else {
			var oldtotal = this.items[id].total;
			var oldquantity = this.items[id].quantity;
			this.items[id].quantity = typeof force != 'undefined' ? quantity
					: this.items[id].quantity + quantity;
			this.items[id].price = round_mod(price, this.precision);
			this.items[id].total = round_mod(this.items[id].quantity
					* this.items[id].price, this.precision);
			this.total = round_mod(this.total - oldtotal + this.items[id].total, this.precision);
			this.quantity = this.quantity - oldquantity + this.items[id].quantity;
		}
		$(window).triggerHandler('add2cart', {'cart': this, 'params':{'id':id, 'price':price, 'quantity':quantity, 'force':force}});
		this.save();
	};
	this.remove = function(id) {
		this.load(this.name);
		this.total -= this.items[id].total;
		this.quantity -= this.items[id].quantity;
		if (typeof this.items[id] != 'undefined') {
			delete this.items[id];
		}
		$(window).triggerHandler('remove2cart', {'cart': this, 'params':{'id':id}});
		this.save();
	};
	this.save = function() {
		var obj = this;
		var save = {};
		for (var prop in obj) {
			if (prop=='items' || prop=='total' || prop=='quantity')	save[prop] = obj[prop];
		}
		$.cookie(obj.name, JSON.stringify(save), {
			path : '/',
			expires : this.expire
		});
	};
	this.load = function(name) {
		var cook = $.cookie(name);
		if (cook!==null) {
			try {
				var data = JSON.parse(cook);
			} catch (e) {}
			if (data!==null) {
				for (var prop in data) {
					this[prop] = data[prop];
				}
			}
		}
		$(window).triggerHandler('load2cart', {'cart': this});
		return this;
	};
};
var CartItem = function() {
	this.quantity = 0;
	this.price;
	this.total = 0;
};

function round_mod(value, precision) {
	return parseFloat((parseFloat(value)).toFixed(precision));
}


