﻿var worldRankingTable = "";

String.prototype.toOrdinal = function()
{
	var n = this % 100;
	var suffix = ['th', 'st', 'nd', 'rd', 'th'];
	var ord = n < 21 ? (n < 4 ? suffix[n] : suffix[0]) : (n % 10 > 4 ? suffix[0] : suffix[n % 10]);
	return this + ord;
}

function injectWorldRanking(data) 
{
  var prefixLength = "<postresults>".length-1;
  var suffixLength = "</postresults>".length-1;
  var html = data.results[0].trim();
  worldRankingTable = html.substring(prefixLength, html.length - suffixLength);
}

$(document).ready(function () 
{
 	// inject world ranking table
 	$('#worldRanking').html(worldRankingTable);
 	// remove hyperlinks in downloaded html
 	$('#worldRanking a').replaceWith(function () 
	{
 		return $(this).contents();
 	});
 	// remove paragraphs in downloaded html
 	$('#worldRanking p').replaceWith(function () 
	{
 		return $(this).contents();
 	});
 	// change table css class
 	$('#worldRanking table').removeClass('list');
 	$('#worldRanking table').addClass('worldRanking');
 	// remove sort class in rank th
 	$('#worldRanking th:first').removeClass('sort_asc');
	// remove all rows after 5th row
	$('#worldRanking tbody:last tr:gt(4)').remove();
 	// combine man and woman into single cell and sort out headers
 	$('#worldRanking tr').each(function () 
	{
 		// replace Rank with World Ranking
 		$(this).find('th:eq(0)').html('World<br/>Ranking');
 		// replace Points with IDSF Points
 		$(this).find('th:eq(1)').html('WDSF<br/>Points');
 		// replace man header with couple header
 		$(this).find('th:eq(2)').html('Couple');
 		// combine man and woman data cells
 		$(this).find('td:eq(2)').append(function (index, html) 
		{
 			return ' & ' + $(this).next().html();
 		});
 		// remove woman column
 		$(this).find('td:eq(3)').remove();
 		$(this).find('th:eq(3)').remove();
 		// set right align on first two columns
 		$(this).find('td:lt(2)').addClass('right');
 		$(this).find('th:lt(2)').addClass('right');
 	});
	
	// only continue if gary and ming in top 5
	var GMrow = $('#worldRanking tr:contains("Gary Crotaz")');
	if (GMrow.length == 0)
	{
		$('#worldRanking').remove();
	}
	else
	{
 		// set class on gary and ming row
 		GMrow.addClass("garyandming");
 		// if number one ranked, say so
 		if ($('#worldRanking tr:eq(1) td:contains("Gary Crotaz")').length == 1) 
		{
 			var rank = $('#worldRanking tr:eq(1) td:eq(0)').html();
 			$('#worldRanking').prepend('<h3>Gary and Ming are currently the highest ranked English WDSF couple at ' + rank.toOrdinal() + ' in the world.</h3>');
 		}
		// add header
    		$('#worldRanking').prepend('<h2>World WDSF ranking of the top 5 English couples</h2>');

 		// replace worldRanking div with its contents to clean up
    		$('#worldRanking').replaceWith(function () 
			{
 				return $(this).contents();
 			});
	}
 });

