// for normal tunnel creation
function check_country()
{
	var country = document.getElementById('country').value;

	if(country == 'US')
	{
		document.getElementById('us_states').style.display = 'inline';
		document.getElementById('non_us').style.display = 'none';
	}
	else
	{
		document.getElementById('non_us').style.display = 'inline';
		document.getElementById('us_states').style.display = 'none';
	}
}			

document.domain="tunnelbroker.net";
var delay_count = 0;
var found = false;

function display_select_best(on)
{
		xx = document.getElementById('select_td');
		xx.className = on ? 'selectON' : 'selectOFF';
}
			
function display_override(on)
{
		xx = document.getElementById('override');
		xx.style.display = on ? 'inline' : 'none';
}

function display_best(str)
{
		document.getElementById("best").innerHTML = str;
}
			
function display_closest_tunnelbroker()
{
	// This code is "special" in that it allows the code to be called twice
	// and yet only execute the second time around
	//var content = window.frames('best_location').document.body.innerHTML;
	if (delay_count++ < 2) 
	{
	// delay 2 seconds
		display_delay_id = setTimeout("display_closest_tunnelbroker();", 1 * 1000);
		if(0) 
			display_best("Please wait while we check: " + delay_count); 
		else 
		{
			if (delay_count == 1)
				display_best("<img STYLE='vertical-align: middle' src='./images/loader.gif'>");
		}
		return;
	}
	var content = window.frames['best_location'].document.body.innerHTML;
	var ipv4 = content.match(/\b(?:\d{1,3}\.){3}\d{1,3}\b/);
				
	for (ii=0;ii<document.activate.chosen_server.length;ii++) 
	{
		if (document.activate.chosen_server[ii].checked == true) 
		{
				// already picked one - don't use the returned value
				// I removed this code, as it makes testing harder
				// break;
				// clear because when doing a refresh on the page, this is sticky
				document.activate.chosen_server[ii].checked = false;
		}
		if (document.activate.chosen_server[ii].value == ipv4) 
		{
				// bingo! We have a winner
				document.activate.chosen_server[ii].checked = true;
				found = true;
				break;
		}
	}
	if(content == null)
		display_best('unknown - pick a nearest location');
	else
		display_best(content);
			
	if (found) 
	{
		// hide the choices and expose the manual button
		display_select_best(false);
		display_override(true);
	} 
	else 
	{
		// show the choices
		display_select_best(true);
		display_override(false);
	}
}

function override()
{
	display_select_best(true);
	display_override(false);
}
	
$(document.getElementById('best')).ready(function() {
if(document.getElementById('best') != null)
{
	display_closest_tunnelbroker();
}
});
