var cart = {
	jar: null,
	country: null,
	
	initialize: function() {
		this.jar = new CookieJar({
			expires:(24*3)*24*60*60,   // three days in seconds
			path: '/'
		});
		
		if(!this.getItems()) {
			this.jar.put('cartItems', []);
		};
		
		// alert($H({items: this.getItems()}).toJSON());
	},
	
	/** 
	 *	itemData: {
	 *		id: [int],
	 *		name: [string],
	 *		price: [float],
	 *		icon: [string],
	 *		options: [string]
	 *	}
	 *	
	 *	cartItem: {
	 *		count: [int],
	 *		itemData: [itemData]
	 *	}
	**/
	addItem: function(itemData, numberToAdd) {
		var items = this.getItems();
		
		$H(itemData).each(function(pair) {
			if(Object.isString(pair.value)) {
				itemData[pair.key] = pair.value.gsub(/'/, '');
			}
		});
		
		for(var index = 0; index < items.size(); index++) {
			var cartItem = items[index];
				
			if($H(cartItem.itemData).toJSON() == $H(itemData).toJSON()) {
				cartItem.count = parseInt(cartItem.count) + parseInt(numberToAdd);
				this.jar.put('cartItems', items);
				$$('.observesCart').invoke('fire', 'cart:refresh');
				return;
			}
		}
		
		items.push({
			count: numberToAdd,
			itemData: itemData
		});
		
		this.jar.put('cartItems', items);
		$$('.observesCart').invoke('fire', 'cart:refresh');
		// alert(items.toJSON());
	},
	
	getTotalItems: function() {
		var count = 0;
		
		this.getItems().each(function(item) {
			count += parseInt(item.count);
		});
		
		return count;
	},
	
	getTotalDimentions: function() {
		var dimensions = {
			length: 0,
			width: 0,
			height: 0,
			weight: 0
		};
		
		cart.getItems().each(function(item) {
			dimensions.length += (parseInt(item.itemData.dimensions.length) * item.count);
			dimensions.width = Math.max(dimensions.width, parseInt(item.itemData.dimensions.width));
			dimensions.height = Math.max(dimensions.height, parseInt(item.itemData.dimensions.height));
			dimensions.weight += (parseInt(item.itemData.dimensions.weight) * item.count);
		});
		
		return dimensions;
	},
	
	/**
	 *	pairs: [
	 *		{
	 *			index: [int],
	 *			count: [int]
	 *		},
	 *		{
	 *			index: [int],
	 *			count: [int]
	 *		},
	 *	...
	 *	]
	**/
	updateCounts: function(pairs) {
		var items = this.getItems();
		
		pairs.each(function(pair) {
			items[pair.index].count = parseInt(pair.count);
		});
		
		var index = 0;
		while(items[index]) {
			var item = items[index];
			if(!item.count || item.count <= 0) {
				items.splice(index, 1);
				index--;
			}
			index++;
		}
		
		this.jar.put('cartItems', items);
		
		$$('.observesCart').invoke('fire', 'cart:refresh');
		if($('get_shipping_estimate')) $('get_shipping_estimate').fire('dom:click');
	},
	
	clearCart: function() {
		this.jar.put('cartItems', []);
		$$('.observesCart').invoke('fire', 'cart:refresh');
	},
	
	getItems: function() {
		return this.jar.get('cartItems');
	},
	
	getItemTotal: function() {
		var items = this.getItems();
		var total = 0.0;
		
		items.each(function(item) {
			total += item.count * item.itemData.price;
		});
		
		return total;
	},
	
	getShippingTotal: function() {
		var total = 0.0;
		
		if($('shipping_total')) {
			var shippingTotal = parseFloat($('shipping_total').innerHTML);
			total += (shippingTotal >= 0)? shippingTotal:0;
		}
		
		return total;
	},
	
	getTaxTotal: function() {
		if(this.country == 'CA')
			return this.getItemTotal() * 0.05;
		else
			return 0.0;
	},
	
	getSubTotal: function() {
		return this.getItemTotal() + this.getShippingTotal();
	},
	
	getTotal: function() {
		return this.getItemTotal() + this.getShippingTotal() + this.getTaxTotal();
	}
};

document.observe("dom:loaded", function() {
	cart.initialize();
	
	$$('[cartItem]').each(function(item) {
		item.observe('click', function(event) {
			var itemData = item.readAttribute('cartItem').evalJSON();
			var count = 1;
			
			if(Object.isFunction(itemData.count)) 
				count = itemData.count(item);
			else
				count = itemData.count;
			
			delete itemData.count;
			
			if(Object.isFunction(itemData.price)) 
				itemData.price = parseFloat(itemData.price(item));
			
			if(Object.isFunction(itemData.options)) 
				itemData.options = itemData.options(item);
			if(!itemData.options) itemData.options = '';
			
			itemData.original_url = window.location.href;
			
			cart.addItem(itemData, count);
			
			if(Prototype.Browser.IE6) {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0'
					},
					duration: 0.3,
					afterFinish: function() {
						present.remove();
					}
				});
			}
			else {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0',
						bottom: -1 * document.viewport.getScrollOffsets().top + 'px',
						left: $('shopping_cart_drawer').down('.handle .btnCartTab_MyCart').cumulativeOffset().left + 'px'
					},
					duration: 0.4,
					afterFinish: function() {
						present.remove();
					}
				});
				
				if(!$('shopping_cart_drawer').hasClassName('open')) {
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-132px'
						},
						delay: 0.1,
						duration: 0.15
					});
					
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-152px'
						},
						delay: 0.3,
						duration: 0.15
					});
				}
			}
			
			event.stop();
		});
	});
	
	if($('shopping_cart_top_link')) $('shopping_cart_top_link').down('.cartNav').addClassName('observesCart');
	if($('shopping_cart_top_link')) $('shopping_cart_top_link').down('.cartNav').observe('cart:refresh', function(event) {
		this.update('I have ' + cart.getTotalItems() + ' item' + ((cart.getTotalItems() == 1)? '':'s') + ' in my cart');
		if(event.memo != 'quiet')
			new Effect.Highlight(this.identify(), {startcolor: '#F26522', endcolor: '#EAEAEA', keepBackgroundImage: true});
	});
	
	if($('update_cart_total')) $('update_cart_total').observe('click', function(event) {
		var pairs = [];
		$$('#main .cartItem').each(function(cartItem) {
			pairs.push({
				index: cartItem.readAttribute('cartIndex'),
				count: cartItem.down('.amount .txtQtyCart').value
			});
		});
		
		cart.updateCounts(pairs);
		
		event.stop();
	});
	
	$$('[cartMarker]').invoke('observe', 'cart:refresh', function(event) {
		var cartMarker = this;
		cartMarker.show();
		
		cartMarker.up().select('.cartItem').invoke('remove');
		
		cart.getItems().each(function(cartItem, index) {
			var itemDiv = new Element('div').addClassName('cartItem');
			if(index % 2 == 0) itemDiv.addClassName('grey');
			cartMarker.insert({before: itemDiv});
			
			var itemImage = new Element('img', {src: cartItem.itemData.icon});
			itemDiv.insert(itemImage);
			
			var itemProduct = new Element('div').addClassName('product');
			itemProduct.insert(new Element('h2').update(cartItem.itemData.name));
			itemProduct.insert(new Element('p').update(cartItem.itemData.options));
			itemDiv.insert(itemProduct);
			
			var itemAmount = new Element('div').addClassName('amount');
			itemAmount.insert(new Element('input', { type: 'text', value: cartItem.count }).addClassName('txtQtyCart'));
			itemAmount.insert(new Element('p').update('x &nbsp;&nbsp;&nbsp; $ ' + cartItem.itemData.price.toFixed(2)));
			itemDiv.insert(itemAmount);
			
			itemDiv.insert(new Element('div').addClassName('clear'));
			
			itemDiv.writeAttribute('cartIndex', index);
		});
		
		cartMarker.hide();
		
		if($('cart_total')) {
			$('cart_total').update(cart.getTotal().toFixed(2));
			$('GST_total').update(cart.getTaxTotal().toFixed(2));
			
			if(cart.getTaxTotal() > 0)
				$('GST_total_area').show();
			else
				$('GST_total_area').hide();
		}
	});
	
	$('drawer_summary').down('h3').observe('cart:refresh', function(event) {
		this.update(cart.getTotalItems() + ' ITEM' + ((cart.getTotalItems() == 1)? '':'S'));
	});
	
	$('cart_total_drawer').observe('cart:refresh', function(event) {
		this.update(cart.getItemTotal().toFixed(2));
	});
	
	if($('checkout_info')) $('checkout_info').down('#payByCC .price .observesCart').observe('cart:refresh', function(event) {
		this.update(cart.getTotal().toFixed(2));
	});
	
	$$('.observesCart').invoke('fire', 'cart:refresh', 'quiet');
});