var price = Class.create();
price.prototype = {

		initialize: function(price, amount, target) {
			this.total = 0;
			this.price  = $(price);
			this.amount = $(amount);
			this.target = $(target);
			this.actiecode = $('fmactiecode');
			this.events = {
				_change: this.__change.bind(this),
				onComplete: this.onComplete.bind(this)
			}
			//this.amount.observe('keyup', this.events._change);
			this.amount.observe('keyup', this.events._change);
			this.actiecode.observe('keyup', this.events._change);
			this.events._change();
		},
		__change:function(E){
			var amount =  this.amount.getValue();
			var total = amount * parseFloat(this.price.innerHTML.replace(',', '.'));
			//if( $F(this.amount) > 0 && $F(this.amount) <= 5)total += 2.2;
			if( amount > 0)total += 3;
			this.total = ((total*100).round()/100).toFixed(2).replace('.', ',');
			
				var parameters = {
					mode:'actiecode',
					code: $F('fmactiecode')
				}
				var options = Object.extend(this.events, {
					mode: 'get',
					parameters: parameters,
					onSucces: this.events.onComplete
				});
				var regex = /^FD-(\d{6})$/;
				if(regex.test(parameters.code)) this.request = new Ajax.Request(window.location.href ,options);

				this.target.update( this.total );
			$('fmprice').writeAttribute('value', this.total );
		},
		onComplete: function(response){
			this.resp = eval( response.responseText );
			if(!$('advice-required-fmactiecode')){
				var error_div = new Element('span', {id: 'advice-required-fmactiecode', 'class':"validation-advice"});
				this.actiecode.insert({after:error_div});
			}
			var error_div = $('advice-required-fmactiecode');
			if(!this.resp.error){
				var amount =  this.amount.getValue();
				var total = amount * parseFloat(this.price.innerHTML.replace(',', '.'));
				if( amount > 0)total += 3
				total -=	parseFloat(this.resp.korting);
				this.total = ((total*100).round()/100).toFixed(2).replace('.', ',');
				this.target.update( this.total );
				$('fmprice').writeAttribute('value', this.total );
				this.actiecode.writeAttribute('readonly', 'true');
				this.actiecode.stopObserving('keyup', this.events._change);
				error_div.update(this.resp.error_message);
			}else{
				error_div.update(this.resp.error_message);
			}

		}
};

addLoadEvent(
	function(){
		price = new price('price','fmaantal', 'total');
	}
);

