/**
 * Checkout.js - Checkout form functionality
 * 
 * @author  Webstores <info at webstores dot nl>
 *          Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 * 
 * @param {Mixed} form The CSS selector or object reference of the HTMLFormElement
 */
function CheckoutForm(form) {
	this.form = $(form);
	this.construct();
};

CheckoutForm.prototype = {
	/**
	 * @constructor
	 */
	construct: function() {
		if(this.form.length) {
			switch(this.form.attr('name')) {
				case 'checkout-step1':
					this.initStepOne();
					break;
			}
		}
	},
	
	/**
	 * Initialize checkout step 1
	 */
	initStepOne: function() {
		var self = this;
		
		$('.quantity-input', this.form).each(function(i, el) {
			new QuantityField(el, {
				updateDelay: 250,
				onUpdate: function() {
					$.ajax({
						url: self.form.attr('action'),
						cache: false,
						dataType: 'json',
						type: 'POST',
						data: self.form.serialize(),
						success: function(data) {
							self.updateCheckoutForm(data);
						}
					});
				}
			});
		});
		
		$('.datetime select', this.form).change(function() {
			var segments = this.value.split('-');
			document.location = '/carts/changedate/' + segments[0] + '/' + segments[1] + '/' + segments[2];
		});
	},
	
	/**
	 * Update checkout form data
	 * 
	 * @param {Object} data The data in JSON format
	 */
	updateCheckoutForm: function(data) {
		/*
		 * JSON
		 * 
			{
				"subTotals": [
					{
						"showId": "0",
						"subTotal": "&euro; 79,60"
					},
					{
						"showId": "1",
						"subTotal": "&euro; 19,95"
					},
					{
						"showId": "2",
						"subTotal": "&euro; 26,75"
					}
				],
				"ticketsTotal": "&euro; 193,60",
				"administrationCost": "&euro; 1,50",
				"grandTotal": "&euro; 206,55"
			}
		 */
		
		for(var i = 0; i < data.subTotals.length; i++) {
			$('#price-' + data.subTotals[i].showId).html(data.subTotals[i].subTotal);
		}
		
		$('#tickets-total .price').html(data.ticketsTotal);
		$('#service-total .price').html(data.administrationCost);
		$('#grand-total .price').html(data.grandTotal);
	}
};

