var gCart = null;

$(document).ready(function() {
	gCart = new Cart('cart');
	gCart.load();
	log(gCart);
	
	updateTotalProductsInCart();
});

function updateTotalProductsInCart() {
	var total = 0 < gCart.totalProducts ? gCart.totalProducts : '0';
	
	$('#totalItemsInCart').html(total);
}

function Cart(name) {
	var z = this;
	
	z.days = 30;
	z.cartName = name;
	z.items = {};
	z.totalProducts = 0;
	
	z.load = function() {
		var c = $.cookie(z.cartName);
		
		log('cookie: ' + c);
		
		if ('string' == typeof(c) && 0 < c.length) {
			c = c.split('|');
			
			for (var i = 0; i < c.length; ++i) {
				var a = c[i].split('-');
				var p = parseInt(a[0]);
				var q = parseInt(a[1]);
				
				if ('number' == typeof(p) && 0 < p && 'number' == typeof(q) && 0 < q) {
					z.items[p] = q;
				}
			}
		}
		
		z.updateTotal();
	}
	
	z.save = function() {
		var s = '';
		var date = new Date();
                date.setTime(date.getTime() + (z.days * 24 * 60 * 60 * 1000));
		
		for (var i in z.items) {
			if (0 < z.items[i]) {
				s += (i+'-'+z.items[i]+'|');
			}
		}
		
		log('Salvar a cookie:['+z.cartName+'] '+s);
		
		$.cookie(z.cartName, s, { path: '/', expires: date });
	}
	
	z.updateTotal = function() {
		var c = 0;
		
		for (var i in z.items) {
			if ('number' == typeof(z.items[i]) && 0 < z.items[i]) {
				c += z.items[i];
			}
		}
		
		z.totalProducts = c;
		return c;
	}
	
	z.addProduct = function(product_id) {
		if ('number' == typeof(z.items[product_id]) && 0 < z.items[product_id]) {
			z.items[product_id]++;
		} else {
			z.items[product_id] = 1;
		}
		
		z.updateTotal();
		z.save();
	}
	
	z.delProduct = function(product_id) {
		if (z.items[product_id]) {
			z.items[product_id] = 0;
		}
		z.updateTotal();
		z.save();
	}
	
	z.updateProduct = function(product_id, quantity) {
		if ('number' == typeof(product_id) && 0 < product_id && 'number' == typeof(quantity) && 0 <= quantity) {
			z.items[product_id] = quantity;
		}
		z.updateTotal();
		z.save();
	}
	
	z.emptyCart = function() {
		z.items = {};
		
		z.updateTotal();
		z.save();
	}
}
