/**

	Frédéric Saunier
	open-sourcing@tekool.net
	http://www.tekool.net/

	This program is part of a free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

	You can also try : http://www.gnu.org/copyleft/gpl.html

**/

//begin import com.tekool.utils.Relegate;
Relegate = function(){};
Relegate.create = function(t,f)
{
	//Transforme arguments en Array et y applique le `splice`
	var a = new Array();
	for(var i=2; i<arguments.length; i++)
		 a.push(arguments[i]);

	return function()
	{
		//Transforme arguments en Array
		var b = new Array();
		for(var i=0; i<arguments.length; i++)
			 b.push(arguments[i]);

		return f.apply
		(
			t,
			b.concat(a)
		);
	};
}
//end import com.tekool.utils.Relegate;


/*
 * Classe chargée de faire le lien entre les résultats retournés par la fonction *getList* du webservice,
 * les évènements du composant List et les appels à la méthode *convert* de la calculatrice.
 *
 * Dans l'idéal il faudrait redistribuer ces fonctionnalités dans une ou plusieurs classe de contrôle.
 */
function EuroConverterList
(
	lstCurrenciesList,
	tiEuro,
	tfConvertedLabel,
	tiConverted,
	calc
)
{
	//Initialisation référence aux composants
	this.lstCurrenciesList = lstCurrenciesList;
	this.tiEuro = tiEuro;
	this.tfConvertedLabel = tfConvertedLabel;
	this.tiConverted = tiConverted;

	this.calc = calc;
	this.calc.onConvert = Relegate.create(this, this.convert);

	// L'évènement "changement de sélection" sur le composant List est directement supportée par la classe
	this.lstCurrenciesList.onchange = Relegate.create(this, this.onLstCurrenciesListChange);
	
	//Initialisation des variables de classe
	this.hasResult = false;
}

/*
 * Méthode chargée de recevoir la liste des taux de changes retournée par le webservice
 */
EuroConverterList.prototype.onGetListResult = function(aCurrenciesList)
{
	this.hasResult = true;

	this.currenciesList = aCurrenciesList;

	var i;
	for(i=0; i<this.lstCurrenciesList.options.length; i++)
		this.lstCurrenciesList.remove(i);

	for(i=0; i<this.currenciesList.length; i++)
	{
		var oOption = document.createElement("OPTION");
		var oLabel = document.createTextNode(this.currenciesList[i].labelFrench);
		this.lstCurrenciesList.options.add(oOption);
		oOption.appendChild(oLabel);

		oOption.value = this.currenciesList[i].code;
	}

	//Un calcul est fait avec les valeurs par défaut pour initialiser l'application 
	this.lstCurrenciesList.selectedIndex = 0;
	this.calc.convert();

}

/*
 * Fonction chargée de convertir la monnaie exprimée en Euro dans le champ Euro de la calculatrice
 * Les valeurs sont directement affichées dans l'interface
 */
EuroConverterList.prototype.convert = function(valueEuro)
{
	if(!this.hasResult)
		return;

	//Le taux de change correspondant à celui sélectionné dans le composant *lstCurrenciesList* est recherché
	//dans liste obtenue par l'appel au webservice
	var oCurrency = this.inList(this.currenciesList,this.lstCurrenciesList);
	if(oCurrency == null)
		return;
	
	var valueConverted = Math.round(valueEuro*oCurrency.rate*100000)/100000;

	//La chaîne de résultat affichée est formatée pour la présentation des nombres à virgule
	this.tiConverted.value = this.formatCurrency(valueConverted);

	//Le nom de la valeur monétaire dans laquelle est convertie celle de provenance est affichée
	this.tfConvertedLabel.value = oCurrency.labelFrench;
}

/*
 * Fonction support de l'évènement "changement de sélection" sur le composant List
 */
EuroConverterList.prototype.change = function(evt)
{
	this.calc.convert();
}

/*
 * Retourne l'entrée du tableau des valeurs retournées par le webservice
 * à partir de celle sélectionnée dans un des deux composants *List*  
 */
EuroConverterList.prototype.inList = function(aList,lstList/*:Select*/)
{
	var i;
	for(i=0; i<aList.length; i++)
		if(aList[i].code == lstList.options[lstList.selectedIndex].value)
			return aList[i];

	return null;
}

/*
 * Formate une valeur monétaire pour en améliorer la présentation
 */
EuroConverterList.prototype.formatCurrency = function(value)
{
	var arr = value.toString().split('.');
	var intPart = arr[0];
	
	if(arr[1] != null && parseInt(arr[1]))
	{
		var floatPart = arr[1];

		//Le nombre à virgule présenté aura toujours au moins 2 chiffres aprés la virgule
		if(floatPart.length == 1)
			floatPart = floatPart + '0';
		else
		{
			var i;
			var trim = null;
			for(i=floatPart.length-1; i>1; i--)
				if( floatPart.substr(i,1) == '0')
					trim = i;
				else
					break;

			if(trim != null)
				floatPart = floatPart.substr(0,trim);
		}
		return intPart + '.' + floatPart;
	}
	else
		return intPart;
}

EuroConverterList.prototype.onLstCurrenciesListChange = function()
{
	this.convert(this.calc.getValue());
}