/* File: donation.js */
// === constants ===============================================================

// Language strings for data entry error messages
var DonateMsgs = {
	'choose_en':	'Please choose at least one project to support',
	'choose_es':    'Elige por lo menos un proyecto que quiere apoyar',
	'choose_fr':	'Veuillez choisir au moins un projet à soutenir',

	'minimum_en':	'Due to processing costs, the smallest donation we can accept is % %',
	'minimum_es':	'A causa de costes de procesamiento, la donación mínima que podamos aceptar és de % %',
	'minimum_fr':	'Compte tenu les frais de traitement, le montant minimal d\'une donation est de % %',

	'wholeNo_en':	'Please enter whole numbers',
	'wholeNo_es':	'Favor usar cifras enteras',
	'wholeNo_fr':	'Veuillez mettre des chiffres en entier SVP'
};

// What's the minimum amount that can be donated for each currency?
var MinAmounts = {'CHF':10,'EUR':5,'GBP':5,'USD':10};
// === functions ===============================================================
// (Somewhat) browser-independent function
function getElem(elemId) {
	if (document.getElementById && document.getElementById(elemId))
		return document.getElementById(elemId);
	else if (document.all && document.all(elemId))
		return document.all(elemId);
	else
		return false;
}
// Get a message in a specific language, inserting args if applicable
function getMsg(tag) {
	var msg = DonateMsgs[tag + '_' + window.lan];
	if (arguments.length == 2) {
		var strArgs = arguments[1];
		for (var i=0; i<strArgs.length; i++)
			msg = msg.replace(/%/, strArgs[i]);
	}

	return msg;
}
// Computes total and checks for integers as a freebie
// Returns true if OK and false if a field has a non-integer
function recalc(f) {
    var total = 0;
	var projStr = '';
	var errMsg = '';
	var e, resKey, resVal;
    for (var i=0; i<f.length; i++) {
		var e = f.elements[i];
		resKey = e.name.match( /^amount_(\w+)/ );
		if (resKey != null) {
			if (e.value.length > 0) {
				resVal = e.value.match( /^\s*(\d+)\s*$/ );
				if (resVal != null) {
					total += parseInt(resVal[1]);  // addition, not concatenation please
					projStr += resKey[1] + '=' + resVal[1] + ',';
				} else {
					errMsg = getMsg('wholeNo');
					break;
				}
			}
		}
	}
	if (projStr.length > 0) projStr = 'projects=' + projStr.replace(/,$/, '');
	f.elements.custom.value = projStr;
	// Show what ever integers we found
	e = getElem('total-text');
	e.innerHTML = total;
	f.elements.amount.value = total; 
	// Were any numbers entered?
	if ((errMsg == '') && (total == 0)) errMsg = getMsg('choose');
	// Is the total less than the minimum amount accepted?
	if (errMsg == '') {
		e = getElem('currency_code');
		var minAmount = MinAmounts[e.value];
		if (total < minAmount)
			errMsg = getMsg('minimum', [e.value, minAmount]);
	}
	if (errMsg != '') alert(errMsg);
	return (errMsg == '');
}

// Event handler called on form submission
function doSubmit() {
	// Use ICV routine to check required fields in the General Info box
	if ( !validate(this) ) return false; 
	// Check and recalculate our Projects box
	var ok = this.recalc();
	// If OK then modify a couple form values
	if (ok) {
		this.elements.amount.value += '.00';
		this.elements.lc.value = PayPalLang;  // defined in donation.cus
		// We pass project list & salutation in the special PayPal 'custom' element
		this.elements.custom.value += encodeURI( '&salutation=' + this.elements.salutation.value );
		// country?
	}
	return ok;
}
// Bootstrap...
oldOnLoad = window.onload;
window.onload = function() {
	if (oldOnLoad) oldOnLoad();
	var form = getElem('form_donate_jbr');
	form.recalc = recalc;
	form.onsubmit = doSubmit;
}
