/**
 * Custom scripts
 *
 * Requires Prototype 1.6.
 *
 * @author Tournier Guillaume <guillaume@ciblo.net>
 * @legals © 2008 Ciblo SA.
 */

var REG_ID = /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/;
var REG_IDS = /(id="[^_\-](?:[A-Za-z0-9\-\_]*)[_]).*?(")/g;

function bindIntegerFields() {
	$$('*[id*="Integer"]').each(function(field) {
		new Field.Observer(field, 0.3, function() {
			field.setValue($F(field).replace(/[^\d\-]/g, ''));
		});
	});
} // bindIntegerFields

function bindFloatFields() {
	$$('*[id*="Float"]').each(function(field) {
		new Field.Observer(field, 0.3, function() {
			field.setValue($F(field).replace(/,/g, '.').replace(/[^\d\-\.]/g, ''));
		});
	});
} // bindFloatFields

function bindCurrentLoans() {
	var payment = $('totalPayment'), funds = $('totalFunds'),
		paymentToKeep = $('totalPaymentToKeep'), fundsToKeep = $('totalFundsToKeep'),
		paymentToTake = $('totalPaymentToTake'), fundsToTake = $('totalFundsToTake');
	if (!payment || !funds || !paymentToKeep || !fundsToKeep || !paymentToTake || !fundsToTake) return;
	var sum = function(acc, f) { return acc += new Number($F(f)); };
	var ksum = function(acc, f) {
		var keep = $('cbxToTake_' + f.id.replace(REG_ID, '$1'));
		return keep && 0 == $F(keep) ? acc += new Number($F(f)) : acc;
	}
	var tsum = function(acc, f) {
		var keep = $('cbxToTake_' + f.id.replace(REG_ID, '$1'));
		return keep && 1 == $F(keep) ? acc += new Number($F(f)) : acc;
	}
	var calc = function() {
		var pFields = $$('*[id^="edtFloatPayment"]'),
			fFields = $$('*[id^="edtFloatRemainingFunds"]'); 
		payment.update(pFields.inject(0, sum).toFixed(2));
		funds.update(fFields.inject(0, sum).toFixed(2));
		paymentToKeep.update(pFields.inject(0, ksum).toFixed(2));
		fundsToKeep.update(fFields.inject(0, ksum).toFixed(2))
		paymentToTake.update(pFields.inject(0, tsum).toFixed(2));
		fundsToTake.update(fFields.inject(0, tsum).toFixed(2));
	}
	$$('*[id^="edtFloatPayment"]')
			.concat($$('*[id^="edtFloatRemainingFunds"]'))
			.concat($$('*[id^="cbxToTake"]')).each(function(field) {
		new Field.Observer(field, 0.3, calc);
	});
	calc();
	$$('*[id^="cbxLoanType"]').each(function(field) {
		var disableDate = function(field) {
			var parent = field.up('tr');
			if (!parent) return;
			var index = field.selectedIndex,
				endOfLoan = parent.down('*[id^="edtEndOfLoan"]'),
				payment = parent.down('*[id^="edtFloatPayment"]');
			endOfLoan && endOfLoan.writeAttribute('disabled', [3, 6].include(index));
			payment && payment.writeAttribute('disabled', 6 == index);
		}
		new Field.Observer(field, 0.3, disableDate);
		disableDate(field);
	});
	
} // bindCurrentLoans

function bindNewCurrentLoan() {
	var link = $('newCurrentLoan'), tbody = $('currentLoans');
	if (!link || !tbody) return;
	link.observe('click', function(e) {
		e.stop();
		var children = tbody.childElements(), size = children.length;
		if (0 == size) return;
		var clone = children.last().cloneNode(true);
		tbody.insert('<tr>' + clone.innerHTML.replace(REG_IDS, '$1' + size + '$2') + '</tr>');
		
	});
} // bindNewCurrentLoan

function bindTotal(total, fields) {
	var func = function(f) { return !f; };
	if (!total || !fields || fields.any(func)) return;
	var calc = function(total, fields) {
		var value = fields.inject(0, function(acc, f) {
			var value = $F(f).replace(/^.*?([0-9]+).*?$/, '$1')
			return acc += new Number(isNaN(value) ? 0 : value);
		});
		total.setValue(isNaN(value) ? '' : value);
	}
	fields.each(function(field) { new Field.Observer(field, 0.3, calc.curry(total, fields)); });
	calc(total, fields);
} // bindTotal

// bind totalRevenues & totalCosts
function bindTotals() {
	bindTotal($('edtIntegerTotalCosts'), $('edtIntegerHomeLoanCosts',
		'edtIntegerConsumerCreditCosts', 'edtIntegerRent',
		'edtIntegerAlimonyGiven', 'edtOtherCosts'));
	bindTotal($('edtIntegerCoTotalCosts'), $('edtIntegerCoHomeLoanCosts',
		'edtIntegerCoConsumerCreditCosts', 'edtIntegerCoRent',
		'edtIntegerCoAlimonyGiven', 'edtCoOtherCosts'));
	bindTotal($('edtIntegerTotalRevenues'), $('edtIntegerWages', 'edtIntegerBnc',
		'edtIntegerBic', 'edtIntegerDisabilityPension1',
		'edtIntegerDisabilityPension2',
		'edtIntegerAlimonyCollected', 'edtIntegerLandRevenues',
		'edtIntegerFamilyAllowance', 'edtOtherRevenues'));
bindTotal($('edtIntegerCoTotalRevenues'), $('edtIntegerCoWages', 'edtIntegerCoBnc',
		'edtIntegerCoBic', 'edtIntegerCoDisabilityPension1',
		'edtIntegerCoDisabilityPension2',
		'edtIntegerCoAlimonyCollected', 'edtIntegerCoLandRevenues',
		'edtIntegerCoFamilyAllowance', 'edtCoOtherRevenues'));
} // bindTotals

function bindPreliminaryAgreement() {
	var checkbox = $('chkPreliminaryAgreement'), panel = $('preliminaryAgreementPanel');
	if (!checkbox || !panel) return;
	var change = function() {
		panel.style.visibility = checkbox.checked ? 'visible' : 'hidden';
		if (!checkbox.checked) panel.select('input').invoke('clear');
	}
	checkbox.observe('click', change);
	change();
} // bindPreliminaryAgreement

function bindOutside() {
	var choice = $('cbxOutside'), panel1 = $('cityContent'),
		panel2 = $('countryContent');
	if (!choice || !panel1 || !panel2) return;
	var change = function() {
		if ('0' == $F(choice)) {
			panel2.hide().select('input').invoke('clear');
			return panel1.show();
		}
		panel2.show();
		panel1.hide().select('input').invoke('clear');
		panel1.select('select').invoke('update', '');
	}
	choice.observe('click', change);
	change();
} // bindOutside

function bindCoLoaner() {
	var choice = $('cbxCoLoan'), associated = $$('p.coLoaner');
	if (!choice || 0 == associated.length) return;
	var change = function() {
		associated.each(function(elt) {
			if ('0' != $F(choice)) return elt.show();
			elt.hide().select('input').invoke('clear');
			elt.select('span.age').invoke('update', '');
		});
	}
	choice.observe('click', change);
	change();
} // bindCoLoaner

function bindCreditPaid() {
	var checkbox = $('chkCreditPaid'), panel = $('creditPaidPanel');
	if (!checkbox || !panel) return;
	var change = function() {
		panel.style.visibility = checkbox.checked ? 'hidden' : 'visible';
		if (checkbox.checked) panel.select('input').invoke('clear');
	}
	checkbox.observe('click', change);
	change();
} // bindCreditPaid

function bindGuarantee() {
	var guarantee = $('cbxReqGuarantee'), fields = $('edtReqZipCode',
		'cbxReqHomeowner', 'edtReqIntegerEstimation', 'chkCreditPaid',
		'edtIntegerRemainingAmount');
	if (!guarantee) return;
	func = function() {	fields.each(function(f) {
		f.writeAttribute('disabled', $F(guarantee) == 'Aucune');
	}); }
	new Field.Observer(guarantee, 0.3, func);
	func();
} // bindGuarantee


document.observe('dom:loaded', function() {
	bindCreditPaid();
	bindCoLoaner();
	bindOutside();
	bindPreliminaryAgreement();
	bindCurrentLoans();
	bindNewCurrentLoan();
	bindTotals();
	bindIntegerFields();
	bindFloatFields();
	bindGuarantee();
});
