var ShoppingCart = new Class({
	cartNode: null,
	productsContainer: null,
	
	productTemplateNodes: null,
	
	products: new Array(),
	
	request: null,
	
	orderButton: null,
	
	urls: {
		refresh: '/set/shoppingCart/refresh',
		add: '/set/shoppingCart/add/',
		remove: '/set/shoppingCart/remove/',
		changeAmount: '/set/shoppingCart/changeAmount/',
		order: '/afrekenen/stap1/'
	},
	
	initialize: function() {
		this.cartNode = document.getElement('.shoppingCart');
		if(!$chk(this.cartNode))
			return;
		this.productsContainer = this.cartNode.getElement('tbody');
		
		this.productTemplateNodes = new Hash({
			header: this.cartNode.getElement('.productTemplate.productHeader').clone()
		});
		
		this.request = new Request.JSON({
			onSuccess: this.updateCart.bindWithEvent(this)
		});
		
		this.orderButton = $('order'); 
		this.orderButton.addEvent('click', this.orderCart.bindWithEvent(this));
		
		this.initOrderingProducts();
		
		this.refresh();
	},
	
	initOrderingProducts: function() {
		var orderButtons = $$('button[name=order]'),
			orderButton,
			amountInput,
			breadOption,
			productId, i
		for(var i=0; i<orderButtons.length; i++) {
			orderButton = orderButtons[i];
			productId = orderButton.get('id').replace('order_product_', '');
			amountInput = $('amount_product_'+productId);
			breadOption = $('breadOption_product_'+productId).get('value') == 1;
			if(breadOption) {
				orderButton.addEvent('click', this.chooseWhiteBrown.bindWithEvent(this, [productId, amountInput]));
			} else {
				orderButton.addEvent('click', this.addProduct.bindWithEvent(this, [productId, amountInput]));
			}
		}
	},
	
	getProducts: function() {
		if(!$chk(this.products))
			return new Array();
		else
			return this.products;
	},
	
	setProducts: function(products) {
		this.products = products;
	},
	
	refresh: function() {
		this.request.send({
			url: this.urls.refresh,
			method: 'get'
		});
	},
	
	updateCart: function(responseJSON, responseText) {
		this.setProducts(responseJSON.products);
		this.renderProducts();
		this.setTotal(responseJSON.total);
	},
	
	renderProducts: function() {
		var products = this.getProducts(),
			productHeaderTemplate = this.productTemplateNodes.get('header'),
			productHeaderRow,
			productAmountInput,
			productRemove,
			productTotalRow,
			product,
			i;
		this.productsContainer.empty();
		if(products.length > 0) {
			for(i=0; i<products.length; i++) {
				product = products[i];
				productHeaderRow = productHeaderTemplate.clone();
				productHeaderRow.getElement('.productName').set('html', product.name);
				
				productAmountInput = productHeaderRow.getElement('input[name=amount]');
				productAmountInput.set('value', product.amount);
				productAmountInput.addEvent('change', this.changeAmount.bindWithEvent(this, product));
				
				productRemove = productHeaderRow.getElement('button.deleteProductButton').addEvent('click', this.removeProduct.bindWithEvent(this, product));
				
				productHeaderRow.getElement('.productUnitPrice').set('html', product.unitPrice);
				this.productsContainer.grab(productHeaderRow);
				
				productHeaderRow.setStyle('visibility', 'visible');
			}
			this.orderButton.setStyle('display', 'inline');
		} else {
			this.productsContainer.grab(
				new Element('tr').grab(
					new Element('td', {
						text: 'Geen items in bestelling',
						'class': 'emptyCartMessage'
					})
				)
			);
			this.orderButton.setStyle('display', 'none');
		}
	},
	
	setTotal: function(total) {
		if(!$chk(total))
			total = '&euro; 0,00';
		this.cartNode.getElement('tfoot').getElement('.total').set('html', total);
	},
	
	changeAmount: function(event, product) {
		event = new Event(event);
		product.amount = event.target.get('value');
		var url = this.urls.changeAmount+product.id+'/'+product.amount;
		if($chk(product.bread)) {
			url = this.urls.changeAmount+product.id+'_'+product.bread+'/'+product.amount;
		}
		this.request.send({
			url: url
		});
	},
	
	setBoxPosition: function(box, position) {
		var dimensions = box.getSize();
		box.setStyles({
			left: (position.x.toInt() - (dimensions.x / 2)) +'px',
			top: (position.y.toInt() - dimensions.y) + 'px'
		});
	},
	
	chooseWhiteBrown: function(event, productId, valueInput) {
		event = new Event(event);
		var position = event.target.getPosition(),
			optionBox = $('breadOptionBox').clone(),
			body = document.getElement('body');
		optionBox.inject(body);
		
		optionBox.set('id', 'breadOptionBox_'+productId);
		optionBox.removeClass('ajaxTpl');
		this.setBoxPosition(optionBox, position);
		
		optionBox.getElement('.white').addEvent('click', this.addProduct.bindWithEvent(this, [productId, valueInput, 'white']));
		optionBox.getElement('.brown').addEvent('click', this.addProduct.bindWithEvent(this, [productId, valueInput, 'brown']));
		optionBox.set('tween', {
			onComplete: function(event) {
				var func = this.hideOptionBox.bindWithEvent(this, optionBox);
				optionBox.store('hideEvent', func);
				document.getElement('body').addEvent('click', func);		
			}.bindWithEvent(this)
		});
		optionBox.fade(0, 1);
	},
	
	addProduct: function(event, productId, valueInput, color) {
		var amount = valueInput.get('value').toInt(),
			optionBox = $('breadOptionBox_'+productId),
			url;
		if(isNaN(amount)) {
			alert('Het aantal moet een geheel getal zijn')
		} else {
			if($chk(color)) {
				url = this.urls.add+productId+'_'+color+'/'+amount;
			} else {
				url = this.urls.add+productId+'/'+amount;
			}
			this.request.send({
				url: url
			});
		}
		
		if($chk(optionBox)) {
			this.hideOptionBox(event, optionBox);
		}
		
		this.showInChartNotifyBox($('order_product_'+productId));
		
		valueInput.set('value', 1);
	},
	
	hideOptionBox: function(event, optionBox, func) {
		var func = optionBox.retrieve('hideEvent');
		
		optionBox.set('tween', {
			onComplete: function(event) {
				this.destroy();
			}.bindWithEvent(optionBox)
		});
		optionBox.fade(1, 0);
		
		if($chk(func)) {
			document.getElement('body').removeEvent('click', func);
		}
	},
	
	removeProduct: function(event, product) {
		var url = this.urls.remove+product.id;
		if($chk(product.bread)) {
			url += '_'+product.bread;
		}
		
		this.request.send({
			url: url
		});
	},
	
	orderCart: function(event) {
		if(this.getProducts().length > 0)
			location.href = this.urls.order;
		else 
			window.alert('Er zijn geen bestelde producten');
	},
	
	showInChartNotifyBox: function(target) {
		var body = document.getElement('body'),
			position = target.getPosition(),
			notifyBox = $('inChartNotify').clone();
		notifyBox.inject(body);
		notifyBox.removeClass('ajaxTpl');
		this.setBoxPosition(notifyBox, position);
		
		notifyBox.set('tween', {
			onComplete: function(event) {
				var func = this.closeNotifyBox.bindWithEvent(this, notifyBox);
				notifyBox.store('hideEvent', func);
				document.getElement('body').addEvent('click', func);		
			}.bindWithEvent(this)
		});
		
		notifyBox.fade(0, 1);
		notifyBox.getElement('.close').addEvent(this.closeNotifyBox.bindWithEvent(this, notifyBox));
		notifyBox.store('closeDelay', this.closeNotifyBox.delay(1500, this, [null, notifyBox]));
	},
	
	closeNotifyBox: function(event, notifyBox) {
		var func = notifyBox.retrieve('hideEvent'),
			closeDelay = notifyBox.retrieve('closeDelay');
		if($chk(closeDelay)) {
			$clear(closeDelay);
		}
		
		notifyBox.set('tween', {
			onComplete: function(event) {
				this.destroy();
			}.bindWithEvent(notifyBox)
		});
		notifyBox.fade(1, 0);
		
		if($chk(notifyBox)) {
			document.getElement('body').removeEvent('click', notifyBox);
		}
	}
});

window.addEvent('domready', function() {
	new ShoppingCart();
});