var x_l, x_m, x_r, y_l, y_m, y_r;
var letters = "ABCDEFGHIJKLMNOPQRSTUVWX";
var radius = 6378.16;

function populateList()
{
    document.writeln("<option value=\"9999\">&lt;&lt; Select a location &gt;&gt;</option>");
    for(i=0; i<s.length; i++)
    {
	document.writeln("<option value=\"" + i + "\">" + s[i][0] + " " + s[i][1] + "</option>");
    }
}

function convTX(form)
{
    if(!loc2deg(trim(form.txname.value.toUpperCase())))
	{
	    document.fqth.reset();
	    return;
	}

    form.txlon.value = Math.ceil(x*1000)/1000;
    form.txlat.value = Math.round(y*1000)/1000;
}

function convRX(form)
{
    if(!loc2deg(trim(form.rxname.value.toUpperCase())))
	{
	    document.fqth.reset();
	    return;
	}

    form.rxlon.value = Math.ceil(x*1000)/1000;
    form.rxlat.value = Math.round(y*1000)/1000;
}

function convRDX(i,form)
{
if(i == 9999) return;

      form.rxname.value = s[i][1];
      form.rxlon.value = Math.ceil(s[i][3]*1000)/1000;
      form.rxlat.value = Math.round(s[i][2]*1000)/1000;
      return;
}

function convTDX(i,form)
{
if(i == 9999) return;

      form.txname.value = s[i][1];
      form.txlon.value = Math.ceil(s[i][3]*1000)/1000;
      form.txlat.value = Math.round(s[i][2]*1000)/1000;
      return;
}

function loc2deg(loc)
{

var gg;

    if(loc.length == 4)
	{
	    loc +="MM";
	    gg = false;
	}
    else gg = true;

    if(loc.length != 6)
	{
	    alert("The locator must have\n4 chars i.e. KP03 or kp03\nor 6 chars i.e. KP03SD or kp03sd");
	    return(false);
	}

    x_l = letters.indexOf(loc.charAt(0));
    x_m = parseInt(loc.charAt(2));
    x_r = letters.indexOf(loc.charAt(4));
    y_l = letters.indexOf(loc.charAt(1));
    y_m = parseInt(loc.charAt(3));
    y_r = letters.indexOf(loc.charAt(5));

    if(x_l<0 || x_l>17 || y_l<0 || y_l>17 || isNaN(x_m) || isNaN(y_m) || x_r<0 || x_r>23 || y_r<0 || y_r>23)
	{
	    alert("The locator must be\nin the range of\nAA00AA .... RR99XX");
	    return(false); 
	}
    x = x_l*10 + x_m + x_r/24;
    if(gg) x = x + 1/48;
    x *= 2;
    x -= 180;

    y = y_l*10 + y_m + y_r/24;
    if(gg) y = y + 1/48;
    y -= 90;

    return(true);
}

function trim(str)
{
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

