var elements = new Array();
var total = null; var totalCartes = null;
var inputTotalPrix = null; var inputTotalNombre = null; var inputPrix = null;
var tarifsKeys = new Array('0', '300', '750', '1000', '2000', '3000', '5000', '10000');
var tarifsValues = new Array('5.00', '4.00','3.80','3.50','3.30','3.00','2.80','2.50');

window.onload = init;

function init()
{
	// hide from older browsers
	if (document.getElementById && document.createTextNode) {
		// put your code here
		
		// calculate total
		if ((total = $('total')) &&
			(totalCartes = $('total-cartes')) &&
			(inputPrix = $('prix')) &&
			(inputTotalPrix = $('total-prix')) &&
			(inputTotalNombre = $('total-nombre'))) {
			
			// set listeners on additions elements
			elements = getElements('cartes');
			setListeners(elements);
			
			// set final update onsubmit the form (because of the auto-fill)
			form = $('form');
			form.onsubmit = function() { updateTotal() }
			
			// update total right now
			updateTotal();
			
			
		}
		
		// reset email input color
		var email = null;
		if (email = $('email')) {
			email.onkeypress = function() {
				this.style.color = '#000';
			}
		}
	}
}

function $(id)
{
	return document.getElementById(id);
}


function getElements(id)
{
	var a = new Array();
	var list = $(id);
	var inputs = list.getElementsByTagName('input');
	
	for (var i = 0; i < inputs.length; i++) {
		var e = inputs[i];
		a[e.id] = e;
	
	}
	/*
	for (var i = 0; i < ids.length; i++) {
		if (tmp = $(ids[i])) {
			a[ids[i]] = tmp;
		}
	}
	*/
	return a;
}

function setListeners(e) 
{
	for (key in e) {
		e[key].onblur = function() {
			updateTotal();
		}
		e[key].onkeypress = function() {
			this.style.color = '#000';
		}
	}
}

function updateTotal()
{
	var nombre = 0; var prix = 0;
	for (key in elements) {
		var n = new Number(elements[key].value);
		if (n >= 0) { 
			nombre += n * 10;
		} else {
			elements[key].style.color = 'red';	
		}
		
	}
	prix = getTarif(nombre);
	totalPrix = nombre * prix;
	total.firstChild.nodeValue = 'CHF ' + totalPrix + '.-';
	totalCartes.firstChild.nodeValue = ' pour ' + nombre + ' cartes.';
	
	totalCartes.firstChild.nodeValue = ' ';
	
	inputPrix.value = prix;
	inputTotalPrix.value = totalPrix;
	inputTotalNombre.value = nombre;
	if (nombre > 300) {
		total.firstChild.nodeValue = 'envoyez ce formulaire pour recevoir une offre personnalisée.';
	}
}

function getTarif(nb)
{
	if (tarifsKeys.length != tarifsValues.length) 
		throw new Error('bad tarifs arrays lengths');
	for (var i = tarifsKeys.length; i >= 0; i--) {
		if (nb >= tarifsKeys[i])
			return tarifsValues[i];
	}
}
