String.prototype.trim = function() {
	// Trim from beginning
	a = this.replace(/^\s+/, '');
	// Trim from end
	a = a.replace(/\s+$/, '');
	// Get rid of duplicate spaces...
	return a.replace(/\s+/g, ' ');
};

$(document).ready(function() {
	$('#convert').click(function() {
	$('<div class="result">' + convert() + '</div>')
		.insertAfter( $("#convert") )
		.slideDown('slow')
		.animate({opacity: 1.0}, 60000)
		.fadeOut('slow', function() {$(this).remove();});
	});
	// Attach events to radio buttons
	$('#valuuta_data > tbody > tr > td > input').click(function() {
		// Get new base currency name and value
		rebuild(this.value, $(this).parent().parent().attr('id'));
	});
	// Do not fire events on enter press..
	$('#converter').submit(function() { return false; });
	// Reset the form
	$('#radios')[0].reset();
});

function rebuild(base, name) {
	// Fetch all the rows
	var rows = $('#valuuta_data > tbody').children('tr');
	// Replace currency in gold cell
	$('#XAU > td.currency > a').html("Gold (" + name + "/oz)");
	// And calculate new values
	rows.each(function (i) {
		var val = "";
		// We leave the base currency cell empty
		if ($(this).attr('id') != name) {
			val = $(this).children('td').children('input').val();
			val = (val/base).toFixed(7);
		}
		$(this).children('.rate').html(val);
	});
}
function fetchval(currency) {
	return $('#' + currency.toUpperCase() + ' > td > input').val()
}
function convert() {
	var errmsg = false;
	var msg = "<div class=\"message\">How much is<br />24 US dollars in British pounds?<br />Type in <b>24 usd gbp</b> and click \"Calculate\"</div>";
	var debug;
	var formula = $('#formula').val().trim();
	var items = formula.split(' ');
	var sum, from, to;
	if (formula.length >= 8 && items.length == 3) {
		// Get our covertable amount...
		if (isNaN(items[0])) {
			errmsg = "<div class=\"message\">Error: \"" + items[0] + "\" is not a number!</div>";
		} else {
			sum = items[0];
		}
		// Get FROM amount...
		if (!errmsg) {
			from = fetchval(items[1]);
			if (!from || isNaN(from)) {
				errmsg = "<div class=\"message\">Error: Currency \"" + items[1] + "\" not found.</div>";
			}
		}
		if (!errmsg) {
			to = fetchval(items[2]);
			if (!to || isNaN(to)) {
				errmsg = "<div class=\"message\">Error: Currency \"" + items[2] + "\" not found.</div>";
			}
		}
	} else {
		errmsg = " ";
	}
	// Build output...
	if (errmsg) {
		msg = errmsg + msg;
	} else {
		// Calculate...
		var tot = sum * (from / to);
		msg = sum + " " + items[1] + " = " + tot.toFixed(2) + " " + items[2];
	}
	// Debug info...
	// msg = msg + "<br />DEBUG: " + items + " - " + items.length + " - " + from + " | " + to;
	// Return message
	return msg;
}
