var W3CDOM = (document.createElement && document.getElementsByTagName);
window.onload = init;

function init() {

  if (!W3CDOM) return;

  var list = document.getElementsByTagName ('input');
    if (! list)
      return;
  for (var i = 0; i < list.length; ++i){
    if (list[i].id.substring(0, 6) == 'submit' && ! list[i].onclick) {
      list[i].onclick = processDonation;
    }
  }

}

function processDonation() {

	var amount = document.getElementById('amount'+this.id.substring(6)).value * 1;
	amount = Math.round(amount * 100)/100;
	var fund = document.getElementById('fund'+this.id.substring(6)).value * 1;
	fund = Math.round(fund * 100)/100;
	var price = document.getElementById('price'+this.id.substring(6)).value * 1;
	price = Math.round(price * 100)/100;
  
	var needed = price-fund;
	needed = Math.round(needed * 100)/100;

	if (isNaN(amount) == 1) {
		alert('The amount you wish to donate must be a number.');
		return false;
	} else {
		// numeric
		if (amount>(needed)) {
			// too much
			if(needed < 5){
				// needed < 5 therefore only accept exact amount
				alert('Donation must be £'+needed);
				return false;
			} else {
				alert('Your donation must be less than or equal to the amount needed.');
				return false;
			}
		} else {
			// not too much
			if (amount==(needed)) {
				return true;
			} else {
				// not the exact amount
				if (amount>=5) {
					return true;
				} else {
					// less than £5
					if(needed < 5){
						// needed < 5 therefore only accept exact amount
						alert('Donation must be £'+needed);
						return false;
					} else {
						//
						alert('Minimum donation £5.');
						return false;						
					}
				}
			}
		}
	}

}
