		var BASE_URL = "";
		var CONTENT_URL = BASE_URL + 'medals.js';
		var ROOT = '#medal_board';
		var order = 'gold';

		function padout(number) { return (number < 10) ? '0' + number : number; }

		function bubbleSort(arrayName,length) {
		    for (var i=0; i<(length-1); i++)
		        for (var j=i+1; j<length; j++)
		            if (arrayName[j] < arrayName[i]) {
		                var dummy = arrayName[i];
		                arrayName[i] = arrayName[j];
		                arrayName[j] = dummy;
		            }
		}

		function myObjectToString() {
		    return '' + padout(this.total) + padout(this.gold) + padout(this.silver) + padout(this.bronze) + this.ioc;
		}
		
		Object.prototype.toString = myObjectToString;

		function getMedalBoard(order)
		{
			requestData = $.getJSON(
				CONTENT_URL,
				function(json)
				{
					if(order=='total')
					{
						bubbleSort(json.MedalCounts, json.MedalCounts.length);
						json.MedalCounts.reverse();
					}
					out = '<tr class="medal_board_header"><th><img src="images/medalha_ouro.gif" alt="ouro" title="ouro" width="13" height="14" /></th><th><img src="images/medalha_prata.gif" alt="prata" title="prata" width="13" height="15" /></th><th><img src="images/medalha_bronze.gif" alt="bronze" title="bronze" width="13" height="14" /></th><th><img src="images/total_medalhas.gif" alt="total de medalhas" title="total de medalhas" width="31" height="14" /></th></tr>';
					for(var i=0; i < json.MedalCounts.length; i++)
					{
						if(i<5)
						{
							line =  "<tr><td width='40' class='colocacao'>" + (i+1);
							line += "</td><td height='18' width='97' align='left' colspan='3' class='fundo_verde'>";
							line += json.MedalCounts[i].ioc + "</td></tr><tr class='medal_count'><td>";
							line += json.MedalCounts[i].gold + "</td><td>";
							line += json.MedalCounts[i].silver + "</td><td>";
							line += json.MedalCounts[i].bronze + "</td><td class='total'>";
							line += json.MedalCounts[i].total + "</td></tr>";
							out += line;
						}

						if(json.MedalCounts[i].ioc == 'BRA')
						{
							line =  "<tr><td width='40' class='colocacao'>" + (i+1);
							line += "</td><td height='18' colspan='3' width='97' align='left' class='fundo_verde'>";
							line += json.MedalCounts[i].ioc + "</td></tr><tr class='medal_count'><td>";
							line += json.MedalCounts[i].gold + "</td><td>";
							line += json.MedalCounts[i].silver + "</td><td>";
							line += json.MedalCounts[i].bronze + "</td><td class='total'>";
							line += json.MedalCounts[i].total + "</td></tr>";
							out += line;
						}

					} 
					$(ROOT).html(out);
				}
			);
		}

		
		$(document).ready(function()
		{
			getMedalBoard(order);
			
			$("#choose_order > label > select").change(function()
			{
				getMedalBoard(this.value);
			});
		});

