var active = false;

function init(){
	$('currency_converter').style.display = 'block';
	$('currency_result').style.display = 'none';
	Event.observe('convert_curr', 'click', convertCurrency);
	Event.observe('convert_curr_1', 'click', stopConvertCurrency);
	Event.observe('back_curr', 'click', switchCurr);
}

function switchCurr(){
	
	$('currency_converter').style.display = 'block';
	$('currency_result').style.display = 'none';
	$('convert_curr_1').style.display = 'none';
	$('convert_curr').style.display = 'block';
	$('result_curr').innerHTML = '';
}

function stopConvertCurrency(e){
	active = false;
	$('currency_converter').style.display = 'block';
	$('currency_result').style.display = 'none';
	$('convert_curr_1').style.display = 'none';
	$('convert_curr').style.display = 'block';
	$('result_curr').innerHTML = '';
}

Event.observe(window, 'load', init); 

function convertCurrency(event){
	var from = $('from_curr').value;
	var to = $('to_curr').value;
	var amount = $('amount_curr').value;
	if( !from || from == null || from == '' || !to || to == null || to == '' || !amount || amount == null || amount == ''){
		return;
	}
	active = true;
	$('convert_curr_1').style.display = 'block';
	$('convert_curr').style.display = 'none';
	var params = 'from='+from+'&to='+to+'&amount='+amount;
	
	var url = 'getCurrency.php';
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'post', 
				parameters: params, 
				onComplete: handleCurrencyConvert
			});
}

function handleCurrencyConvert(req){
	if( active == false ) return; 
	var xml = req.responseXML;
	var rootEl = (xml.childNodes[0].tagName == 'root')?xml.childNodes[0]:xml.childNodes[1];
	var res = rootEl.childNodes[2].attributes.getNamedItem('val').value + " " + rootEl.childNodes[0].attributes.getNamedItem('val').value + " = " + rootEl.childNodes[3].attributes.getNamedItem('val').value + " " + rootEl.childNodes[1].attributes.getNamedItem('val').value;
	$('currency_converter').style.display = 'none';
	$('result_curr').innerHTML = res;
	$('currency_result').style.display = 'block';
	 
}
