window.addEvent('domready',function(){
	new Cart();
})

var Cart = new Class({
	initialize: function(){
		$$('tr.item').each(function(el, i){
			
			//remove item action
			el.getElement('.removeBtn').addEvent('click',function(event){
				this.removeFromCart(el)
			}.bind(this))

			//change qty action
			el.getElement('input.qty').addEvent('keyup',function(event){
				//console.log('change');
				//console.log(el.getElement('input.qty').get('value'))
				this.updateQty(el)
			}.bind(this))
		}.bind(this))
	},
	
	removeFromCart: function(el){
		var id = el.get('id');
	
		//make a request to cart
		new Request({	
			url:'requestCodeMarkup.php', 
			async:'false', 
			onSuccess: function(newTotal){ 
				$('grand_total').set('text', newTotal);
				el.dispose();
				//check to see if the cart is empty
				if(!($('cartTable').getElement('tr.item'))){
					$('totalRow').set('html', '<td colspan="5"><p align="center"><br />Your cart is empty.</p></td>')
				}
			}.bind(this) 
		}).send("content=cart&action=removeItem&id="+id);	
		
	},
	
	updateQty: function(el){
		var id = el.get('id');
		var qty = el.getElement('input.qty').get('value')*1
		
		
		//make a request to cart
		new Request({	
			url:'requestCodeMarkup.php', 
			async:'false', 
			onSuccess: function(priceObj){
				var priceObj = JSON.decode(priceObj); 
				$('grand_total').set('text', priceObj['grand_total']);
				el.getElement('td.item_total').set('text', priceObj['item_total']);
			}.bind(this) 
		}).send("content=cart&action=updateQty&id="+id+"&qty="+qty);		
	},
})
