var CartItem = new Class({
	initialize: function(cart, item) {
		this._cart = cart;
		this._item = item;
		this._messages = { confirm: { nl: "Weet u het zeker?", en: "Are you sure?" }};
				
		this._item.getElement('select.license_video_format').addEvent('change', this.onChangeLicenseVideoFormat.bind(this));
		this._item.getElement('select.license_video_format').fireEvent('change');
		
		this._item.getElement('.delete').addEvent('click', this.removeRow.bind(this));
		
		this._cart.getElement('input[name="update_all"]').setStyle('display', 'none');
		
		
	},
	
	onChangeLicenseVideoFormat: function() {
		this.saveItem();
	},

	saveItem: function() {
		var saveRequest = new Request.JSON({
			url: '/cart/updateItem',
			onSuccess: this.onSuccessSaveItem.bind(this),
			data: {
				cart_item_id: this.getCartItemId(),
				license_video_format_id: this.getLicenseVideoFormatId(),
				amount: this.getAmount()
			}
		});
		saveRequest.send();
	},
	
	onSuccessSaveItem: function(response) {
		if (response.error) {
			alert(response.message);
		}
		else {
			this.updateTotalPrice(response.price_formatted);
		}
	},
		
	onSuccessRemoveRow: function(responseJSON) {
		this._item.destroy();
		this.updateTable();
		this.updateTotalPrice(responseJSON.price_formatted);
	},
	
	removeRow: function() {
		var lang = $$('body')[0].hasClass('nl') ? 'nl' : 'en';
		if (window.confirm(this._messages.confirm[lang])) {
			var removeRequest = new Request.JSON({
				url: '/cart/delete',
				data: {
					cart_item_id: this.getCartItemId()
				},
				onSuccess: this.onSuccessRemoveRow.bind(this)
			});
			removeRequest.send();
		}
		return false;
	},
	
	updateTable: function() {
		if (this._cart.getElements('.item').length == 0) {
			this._cart.destroy();
		}
	},
	
	updateTotalPrice: function(price_total) {
		if (this._cart.getElement('.price_total')) {
			this._cart.getElement('.price_total').set('text', price_total);
		}
	},
	
	getCartItemId: function() {
		var el = this._item.getElement('input[name="cart_item_id[]"]');
		if ($chk(el)) {
			return el.getProperty('value');
		}
	},
	
	getLicenseVideoFormatId: function() {
		var el = this._item.getElement('select[name="license_video_format_id[]"]');
		if ($chk(el)) {
			return el.getProperty('value');
		}
	},
	
	getAmount: function() {
		return 1;
	}
});

document.addEvent('domready', function() {
	$$('.cart').each(function(cart) {
		cart.getElements('.item').each(function(item) {
			new CartItem(cart, item);
		});
	});
});