/*Currency converter class*/
var CurrencyConverter = Class.create({
	
	/*An array of quotes*/
	quotes:false,
	
	/*Reference to the a select box with currencies*/
	fromCurrencyList:false,
	
	/*Reference to the a select box with currencies*/
	toCurrencyList:false,
	
	/*last currency used as from*/
	fromCurrency:false,
	toCurrency:false,
	
	fromRate:false,
	toRate:false,
	conversionRate:false,
	result:false,
	formattedResult:false,
	
	/*Input text from*/
	fromAmountInput:false,
	
	fromAmount:false,
	
	/*Div or span to update with results*/
	resultBox:false,
	
	initialize:function(quotes, fromCurr, toCurr, fromInput, resultBox){
		
		this.quotes = quotes;
		this.fromCurrencyList = fromCurr;
		this.toCurrencyList = toCurr;
		this.fromAmountInput = fromInput;
		this.resultBox = resultBox;
		
		this.attachParent();
		this.declareEvents();
		this.update();
	},
	
	attachParent:function(){
		this.fromCurrencyList.currencyConverter = this;
		this.toCurrencyList.currencyConverter = this;
		this.fromAmountInput.currencyConverter = this;
		this.resultBox.currencyConverter = this;
	},
	
	update:function(){
		
		var me;
		if(typeof(this.currencyConverter)=='object'){
			/*Calling as event*/	
			me = this.currencyConverter;
		}else{
			/*calling directly*/
			me = this;
		}
		
		/*Get currencies from select boxes*/
		me.fromCurrency = me.fromCurrencyList.getValue();
		me.toCurrency = me.toCurrencyList.getValue();
		me.fromAmount = me.fromAmountInput.getValue();
		
		if(me.validateInput()!=''){
			return me.validateInput(); 
		}
		
		me.fromRate = me.quotes[me.fromCurrency];
		me.toRate = me.quotes[me.toCurrency];
		
		me.calculate();
		
		me.formattedResult = me.result.numberFormat("#,0.00");
		me.resultBox.update(me.formattedResult);
			
	},
	
	calculate:function(){
		this.conversionRate = (1 / this.fromRate)*this.toRate;
		this.result = this.fromAmount * this.conversionRate;
		return true;
	},
	
	validateInput:function(){
		if(this.fromCurrency==''){
			return 'NO_FROM_CURRENCY';
		}else if(this.toCurrency==''){
			return 'NO_TO_CURRENCY';
		}
		return '';
	},
	
	declareEvents:function(){
		Event.observe(this.fromAmountInput,'keyup',this.update);
		Event.observe(this.fromCurrencyList,'change',this.update);
		Event.observe(this.toCurrencyList,'change',this.update);
		
	}
	
});
