var Cart=new Class({
					  
	'Implements':Options,
	
	'options':{
		
		'data':[],	// Holds the cart items with 0 - id, 1 - qty, 2 - price at time
		'builderFunc':buildSideCart,	// Function that is called after every method,
		'request':null	// References the request class
		
	},
	
	'initialize':function(options){

		this.setOptions(options);
		
		/*	Get cart items for this user */
		
		this.getCartItems();
		
	}

});

Cart.implement({getCartItems:function(){

	/*	Request */

	if(this.options.request) this.options.request.cancel();
	this.options.request=new Request({
	
		'method':'get',
		'url':'/biomechanix/assets/scripts/ecommerce/get-cart-items.php',
		'onSuccess':function(response){
		
			this.options.data=JSON.decode(response);

			/*	Build */
			
			this.build(this.options.data);
		
		}.bind(this)
	
	}).send();

}});

Cart.implement({addToCart:function(productID,quantity,price){

	/*	Housekeeping */
	
	quantity=$pick(quantity,1);
	
	/*	Add to data if not existing, else update */
	
	var found=false;
	this.options.data.each(function(value,key){
	
		if(value[0]==productID){
		
			value[1]=quantity;
			value[2]=price;
			found=true;
			return;
			
		}
	
	});
	
	if(!found) this.options.data.push([Number(productID),Number(quantity),Number(price)]);

	/*	Update cart */
	
	this.updateCart();

}});

Cart.implement({getCartData:function(){

	/*	Get clean data array */
	
	var data=[];
	this.options.data.each(function(value,key){
	
		if(value[0]!=0&&value[1]!=0) data.push(value);
	
	});
	
	return data;

}});

Cart.implement({updateCart:function(form){

	/*	Get cart items */
	
	var data=this.getCartData();

	/*	Request */

	if(this.options.request) this.options.request.cancel();
	this.options.request=new Request({
	
		'method':'post',
		'data':{'cartItems':JSON.encode(data)},
		'url':'/biomechanix/assets/scripts/ecommerce/add-to-cart.php',
		'onSuccess':function(response){

			/*	Build */
	
			this.cart.build(this.cart.options.data);
			
			/*	Submit */
			
			if(this.form) $(form).submit();
		
		}.bind({'cart':this,'form':form})
	
	}).send();

}});

Cart.implement({updateItemQuantity:function(id,qty,price){

	this.options.data.each(function(value,key){
	
		if(value[0]==id){
		
			value[1]=Number(qty);
			value[2]=Number(price);
			
		}
	
	});
	
	/*	Update the cart */
	
	this.updateCart();

}});

Cart.implement({deleteItem:function(id){

	this.options.data.each(function(value,key){
	
		if(value[0]==id){
		
			value[0]=0;
			value[1]=0;
			
		}
	
	});
	
	/*	Update the cart */
	
	this.updateCart();

}});

Cart.implement({clear:function(form){

	/*	Clear */
	
	this.options.data=[];
	this.updateCart(form);

}});

Cart.implement({submit:function(form){

	/*	Build */
	
	this.clear(form);

}});

Cart.implement({build:function(){

	/*	Build */
	
	if(this.options.builderFunc) this.options.builderFunc(this.options.data);

}});