var products, Products = Class.create();

Products.prototype = {
	initialize: function(shipping_costs){
		this.shipping_costs = shipping_costs;
	
		this.summary = $('summary');
		
		this.products = $('products').select('.product').collect(function(product){
			return new Product(product);
		});
		
		this.update();
	},
	
	update: function(){
		str = '';
		total_price = this.shipping_costs;
		
		for(i=0; i<this.products.length; i++){
			this.products[i].element.removeClassName('active');
		
			if(this.products[i].amount.value > 0){
				this.products[i].element.addClassName('active');

				str += '<dl>'
				str += '<dt>' + this.products[i].amount.value + '<span>x</span></dt>';
				str += '<dd><span>' + this.products[i].total_price() + '</span>' + this.products[i].name + '</dd>';
				str += '</dl>'
				
				total_price += (this.products[i].price * this.products[i].amount.value);
			}
		}
		
		str += '<dl>'
		str += '<dt>&nbsp;</dt>';
		str += '<dd><span>' + format_price(this.shipping_costs) + '</span>Verzendkosten</dd>';
		str += '</dl>'
		
		str = '<div class="price">&euro; ' + format_price(total_price) + '</div>' + str;
		
		this.summary.fade({duration: 0.4, to: 0.01});
		window.setTimeout(function(){
			products.summary.update(str);
			products.summary.appear({duration: 0.4});
		}, 500);
	},
	
	get: function(id){
		var product = false;
		this.products.each(function(p){
			if(p.id == id){
				product = p;
			}
		});

		return product;
	}
}

var Product = Class.create();
Product.prototype = {
	initialize: function(element){
		this.element = element;
		this.id = this.element.id.replace('product_', '');

		this.name = this.element.select('h4')[0].innerHTML;
		this.amount = this.element.select('select')[0];
		this.price = this.element.select('.price')[0].innerHTML.replace(',', '.');
		
		Event.observe(this.amount, 'change', function(ev) { products.update(); });
	},
	
	total_price: function(){
		return format_price(this.price * this.amount.value);
	}
}

function format_price(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)) num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10) cents = "0" + cents;
	
	for(var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
		num = num.substring(0,num.length-(4*i+3)) +'.'+ num.substring(num.length-(4*i+3));
	}
	
	return (((sign)?'':'-') + num + ',' + cents);
}

function formHandler(form){
	var URL = document.form.site.options[document.form.site.selectedIndex].value;
	window.location.href = URL;
}

