/**
 * Cart.js - Doe het zelf zonwering cart
 * 
 * @author Webstores <info at webstores dot nl>
 *         Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */
function Cart(form, options) {
	this.form = $(form);
	this.options = options;
	this.construct();
};

Cart.prototype = {
	/**
	 * @constructor
	 */
	construct: function() {
		if(this.form.length) {
			this.options = $.extend({
				priceUrl: '/cart/price'
			});
			
			this.createQuantityFields();
		}
	},
	
	/**
	 * Create quantity fields
	 */
	createQuantityFields: function() {
		var self = this;
		
		$('.quantity-input', this.form).each(function() {
			new QuantityField(this, {
				min: 1,
				updateDelay: 250,
				onUpdate: function() {
					$.ajax({
						url: self.options.priceUrl,
						cache: false,
						dataType: 'json',
						type: 'POST',
						data: self.form.serialize(),
						success: function(data) {
							self.updateCart(data);
						}
					});
				}
			});
		});
	},
	
	/**
	 * Update the cart prices
	 * 
	 * @param {Object} data The JSON response
	 */
	updateCart: function(data) {
		/*
		 * JSON
		 * 
			{
				"subTotals": [
					{
						"productId": "0",
						"subTotal": "&euro; 4.400,00"
					},
					{
						"productId": "1",
						"subTotal": "&euro; 5.600,00"
					}
				],
				"vatTotal": "&euro; 49,00",
				"grandTotal": "&euro; 10.000,00"
			}
		 */
		//for(var i = 0; i < data.subTotals.length; i++) {
		
		$('#total-' + data.subTotals.productId).html(data.subTotals.subTotal);
		//}
		//}
		if(data.subTotals.options != null){
			for(var i = 0; i < data.subTotals.options.length; i++){
				$('#total-opt-'+ data.subTotals.productId +'-'+ data.subTotals.options[i].optionId).html('&euro '+ data.subTotals.options[i].optSubtot);
			}
		}
		
		//$('#vat-total').html(data.vatTotal);
		$('#total-sendcosts').html(data.sendcosts);
		$('#grand-total').html(data.grandTotal);
		return false;
	}
};

