window.addEvent('domready', function() {
	var percentage = 4;
	var nr = 0;
	var total = 0;
	var discount = 0;
	var newtotal = 0;
	var products = $$(document.getElementsByName('products[]'));

	var print_totals = function() {
		$('total').setText(total);
		$('discount').setText(discount);
		$('newtotal').setText(newtotal.round(1));
		$('save').setText((total-newtotal).round(1));
	}
	
	var update_values = function() {
		discount = percentage*nr;
		newtotal = total-discount*total/100;
	}
	
	print_totals();
	
	products.each(function(item) {
		item.setProperty('checked', false);
		item.addEvent('click', function(e) {
			var id = item.getProperty('value');
			var price = $('price'+id).getText().toInt();
			if (item.getProperty('checked')) {
				nr++;
				total = total+price;
				if (item.getProperty('value')==5 && $('pr11').getProperty('checked')) {
					$('pr11').setProperty('checked', false);
					nr--;
					total = total-price;
				}
				if (item.getProperty('value')==11 && $('pr5').getProperty('checked')) {
					$('pr5').setProperty('checked', false);
					nr--;
					total = total-price;
				}
				if (nr>1) {
					update_values();
				} else {
					discount = 0;
					newtotal = total;
				}
			} else {
				nr--;
				total = total-price;
				if (nr<=1) {
					discount = 0;
					newtotal = total;
				} else {
					update_values();
				}
			}
			if (nr<0) {
				nr=0;
			}
			if (total<0) {
				total=0;
			}
			if (newtotal<0) {
				newtotal=0;
			}
			print_totals();
		});
	});
	
	$('prform').onsubmit = function() {
		if (nr==0) {
			alert('Please select the products you want to buy');
			return false;
		} else {
			var prod_array = new Array();
			var i = 0;
			products.each(function(item) {
				if (item.getProperty('checked')) {
					prod_array[i] = item.getProperty('value');
					i++;
				}
			});
			Cookie.set('products', prod_array, {path: "/", duration: 1}); // save this for 1 day
			return true;
		}
	}
	
	$('clear').onclick = function() {
		nr = 0;
		total = 0;
		discount = 0;
		newtotal = 0;
		print_totals();
		products.each(function(item) {
			item.setProperty('checked', false)
		});
	}
});