var req;
var rates;


function onLoad() {
	updateFlag(document.getElementById('from'));
	updateFlag(document.getElementById("to"));
	document.getElementById("amount").value = "";
	updateRates();
}

function updateRates() {
	var url = "/xml/publicwebrates/rates.xml";
	//var url = "./rates.xml";
	req = loadAjax(url, ratesCallback);
	//updateAmount();
	setTimeout("updateRates()", 30 * 1000);

}

function ratesCallback() {
 	if (req && req.readyState == 4) {
	        if (req.status == 200 || req.status == 0) {
			rates = req.responseXML;
			updateAmount();
			//var instrumentList = rates.getElementsByTagName("instrument");
	    		//req = null;	
	        } else {}
    	}
}

function loadAjax(url, myCallback) {
    if (window.XMLHttpRequest) {
        var req = new XMLHttpRequest();
	    req.onreadystatechange = myCallback;
        req.open("GET", url, true);
        req.send(null);
    } else if (window.ActiveXObject) {
        var req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = myCallback;
            req.open("GET", url, true);
            req.send();
        }
    }
   return req;
}

function rtfx_rate(from, to, rate_type) {
	try { 
		if(typeof(req) == "undefined" 
			|| typeof(req.responseXML) == "undefined" 
			|| typeof(req.responseXML.getElementsByTagName) == "undefined" ) return;
	}catch(e) { return; }
	
	var instrumentList = req.responseXML.getElementsByTagName("instrument");
	var rate;
	for(i=0; i < instrumentList.length; i++) {
		var instrName = instrumentList.item(i).getAttribute("name");
		var instr_name = (from + "-" + to);
		if(instrName == instr_name) {
			rate =  instrumentList.item(i).getElementsByTagName(rate_type).item(0).firstChild.nodeValue;
		}
	}
	return rate;
}

function rtfx_any_rate(from, to, rate_type) {
	var rate = rtfx_rate(from, to, rate_type);
	if(rate) return rate;
	rate = rtfx_rate(to, from, rate_type);
	if(rate) return (1 / rate);
	return rate;
}


function  rtfx_cross(cur1, cur2, rate_type) {
		var cross 	= "USD";
		var rateleft  	= rtfx_any_rate(cur1, cross, rate_type);
		var rateright 	= rtfx_any_rate(cur2, cross, rate_type);

		// if not through USD, we are lost
		if ((rateleft == null) || (rateright == null))
			return null;		
		return rateleft / rateright;
}


function rtfx_convert(from, to, amount, rate_type) {
	if(from == to) return amount;

	var rate;
	var convertedAmount;

	rate = rtfx_any_rate(from, to, rate_type);
	
	// ok cross them
	if(!rate) {
		rate = rtfx_cross(from, to, rate_type);
	}	

	return rate * amount;
	
}

function updateFlag(el) {
	var id 		= el.id;
	var currency 	= el.options[el.options.selectedIndex].value;
	var flagImg 	= document.getElementById( id + "_currency");
	flagImg.src	= "http://www.realtimeforex.com/converter/currencies/" + currency + ".gif";
	flagImg.alt 	= currency;
}


function updateAmount() {
	var from 	= document.getElementById("from");
	var to   	= document.getElementById("to");
	var amount 	= document.getElementById("amount");
	var converted 	= document.getElementById("converted");	
	var converted_inverse 	= document.getElementById("converted_inverse");	
	//var highEl	= document.getElementById("high");	
	//var lowEl	= document.getElementById("low");
	

	var bid = rtfx_convert(from.options[from.options.selectedIndex].value,
			to.options[to.options.selectedIndex].value, amount.value, "bid");

	var bid_inverse = rtfx_convert(to.options[to.options.selectedIndex].value,	
			from.options[from.options.selectedIndex].value, amount.value, "bid");

	/*
	var high = rtfx_convert(from.options[from.options.selectedIndex].value,
			to.options[to.options.selectedIndex].value, amount.value, "high");
	
	var low = rtfx_convert(from.options[from.options.selectedIndex].value,
			to.options[to.options.selectedIndex].value, amount.value, "low");

	*/
	var from_currency 	= from.options[from.options.selectedIndex].value;
	var to_currency 	= to.options[to.options.selectedIndex].value;
	
	if(bid && bid.toFixed)	bid = bid.toFixed(2);
	if(bid_inverse && bid_inverse.toFixed)	bid_inverse = bid_inverse.toFixed(2);
	/*
	if(high && high.toFixed) high = high.toFixed(2);
	if(low && low.toFixed) 	low = low.toFixed(2);
	if(low > high) {
		var tmp = low;
		low = high;
		high = tmp;
	} */
	
	converted.innerHTML 	= bid ? formatCurrency(amount.value) + " " + from_currency 
				+ " = " + formatCurrency(bid)  + " " + to_currency : "&nbsp;";
	converted_inverse.innerHTML 	= bid_inverse ? formatCurrency(amount.value) + " " + to_currency 
				+ " = " + formatCurrency(bid_inverse)  + " " + from_currency : "&nbsp;";
	//highEl.innerHTML 	= high ? high : "";
	//lowEl.innerHTML 	= low ? low : "";

}


function formatCurrency(num) {
	num = num.toString().replace(/\'/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents < 10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+"'"+
	num.substring(num.length-(4*i+3));
	// with cents
	return (((sign)?'':'-') + num + '.' + cents);
	//return (((sign)?'':'(') + num  + ((sign)?'':')'));
}




