var BasketCalculator = new Class({
	initialize: function(formEl){
		this.formElement = $(formEl);
		if (this.formElement.getElement("#productprice")) {
		  this.price = this.formElement.getElement("#productprice").getValue();
		} else {
		  this.price = 0;
		}
		
		if (this.formElement.getElement("#quantity")) {
            this.quantityElement = this.formElement.getElement("#quantity");
    		this.quantityElement.addEvent("change", function(){
    			this.update();
    		}.bind(this));
    	}
		
		this.additionalItems = [];
		this.additionalPrices = [];
		
		this.formElement.getElements("input[type=checkbox]").each(function(el, index){
			if($(el).getProperty("value") == "selectall") return;
			
			this.additionalPrices.push($(el.id + "_price").getValue());
			
			$(el).addEvent("click", function(){
				if(el.checked){
					this.add(index);
				} else {
					this.remove(index);
				}
			}.bind(this));
		}.bind(this));
		
		this.additionals = 0;
		
		this.totalElement = this.formElement.getElement("#total");
		this.update();
	},
	
	updateAdditionals: function() {
		this.additionals = 0;
		this.additionalItems.each(function(index){
			//parseFloat decimals are incorrect
			this.additionals = ((100 * this.additionals).round() + (100 * this.additionalPrices[index]).round()) / 100;	
		}.bind(this));
	},
	
	update: function(){
        if (this.quantityElement) {
            this.quantity = this.quantityElement.getValue();
        } else {
            this.quantity = 0;
        }
		this.total = ((100 * this.price).round() * this.quantity) / 100;
		this.writeResult();
	},
	
	add: function(index) {
		var itemExists = this.additionalItems.include(index);
		if(itemExists) {
			this.updateAdditionals();
			this.writeResult();
		}
	},
	
	remove: function(index) {
		this.additionalItems.remove(index);
		this.updateAdditionals();
		this.writeResult();
	},
	
	writeResult: function(){
		this.grandTotal = (((100 * this.total).round() + (100 * this.additionals).round()) / 100).toString();
		if(this.grandTotal.contains(".")){
			if(this.grandTotal.length - this.grandTotal.indexOf(".") < 3)
				this.grandTotal += "0";
		} else {
			this.grandTotal += ".00";
		}
		if (this.totalElement) {
		  this.totalElement.setHTML("&pound;" + this.grandTotal);
		}
	}
});

