LicensePriceCalculator = new Class({
	initialize: function(container) {
		this._container = container;
		
		this._container.getElements('select.license').each(function(select) {
			select.addEvent('change', this.changeLicense.bind(this, select));
			select.fireEvent('change');
		}.bind(this));
		
		this._container.getElements('select.license_video_format').each(function(select) {
			select.addEvent('change', this.changeLicenseVideoFormat.bind(this, select));
			select.fireEvent('change');
		}.bind(this));
	},
	
	changeLicense: function(select) {
		var selected_license_id = select.options[select.selectedIndex].value;
		if (selected_license_id > 0) {
			this.loadLicensePrice({ license_id: selected_license_id });
		}
		else {
			this.reset();
		}
	},
	
	changeLicenseVideoFormat: function(select) {
		var selected_license_video_format_id = select.options[select.selectedIndex].value;
		if (selected_license_video_format_id > 0) {
			this.loadLicensePrice({ license_video_format_id: selected_license_video_format_id });
		}
		else {
			this.reset();
		}
	},
	
	getLicenseId: function() {
		var select = this._container.getElement('select.license');
		if ($chk(select)) {
			return select.options[select.selectedIndex];
		}
	},

	getLicenseVideoFormatId: function() {
		var select = this._container.getElement('select.license_video_format');
		if ($chk(select)) {
			return select.options[select.selectedIndex];
		}
	},

	getAmount: function() {
		return 1;
	},
	
	loadLicensePrice: function(values) {
		var loadLicensePriceRequest = new Request.JSON({
			url: '/cart/getLicensePrice',
			onSuccess: this.onSuccessLoadLicensePrice.bind(this),
			data: $merge({ amount: this.getAmount() }, values)
		});
		loadLicensePriceRequest.send();
	},
	
	onSuccessLoadLicensePrice: function(response) {
		if (response.error) {
			alert(response.message);
		}
		else {
			this.updateLicensePrice(response.price_formatted);
			this.updateLicenseDescription(response.license_description);
		}
	},
	
	updateLicensePrice: function(price) {
		var el = this._container.getElement('.price');
		if (el) {
			el.set('text', price);
		}
	},

	updateLicenseDescription: function(license_description) {
		var el = this._container.getElement('.license_description');
		if ($chk(el)) {
			el.set('text', license_description);
		}
	},
	
	reset: function() {
		this.updateLicensePrice('\u20ac0,00');
		this.updateLicenseDescription('');
	}
});

document.addEvent('domready', function() {
	$$('.license_price_calculator').each(function(container) {
		new LicensePriceCalculator(container);
	});
});