
function apt_get_code(i) {
	var code = apt_get_iata(i);
	if (code.length == 0) 
		code = apt_get_icao(i);
	if (code.length == 0) 
		code = apt_get_faa(i);
	return code;
}

function apt_get_country(i) {
	var idx = apt_binsearch(apt_get_country_code(i), g_apt_ccode_to_ctry, apt_get_ccode_code);
	if (idx >= 0) {
		return apt_get_ccode_name(idx);
	}
	return "";
}

function apt_get_lonlat(i) {
	return apt_lonlat_new(apt_get_lon(i), apt_get_lat(i));
}

function apt_get_idx_by_iata(code) {
	var idx = apt_binsearch(code, g_apt_iata_to_row, apt_get_iata_code);
	if (idx >= 0) {
		return parseInt(apt_get_iata_row(idx));
	}
	return -1;
}

function apt_get_idx_by_icao(code) {
	var idx = apt_binsearch(code, g_apt_icao_to_row, apt_get_icao_code);
	if (idx >= 0) {
		return parseInt(apt_get_icao_row(idx));
	}
	return -1;
}

function apt_get_idx_by_faa(code) {
	var idx = apt_binsearch(code, g_apt_faa_to_row, apt_get_faa_code);
	if (idx >= 0) {
		return parseInt(apt_get_faa_row(idx));
	}
	return -1;
}

function apt_get_idx(code) {
	var code = code.toUpperCase();
	if (code.substr(0, 5) == "IATA:") {
		code = code.substr(5);
		return apt_get_idx_by_iata(code);
	}
	if (code.substr(0, 5) == "ICAO:") {
		code = code.substr(5);
		return apt_get_idx_by_icao(code);
	}
	if (code.substr(0, 4) == "FAA:") {
		code = code.substr(4);
		return apt_get_idx_by_faa(code);
	}
	// try by iata 1st
	var idx = apt_get_idx_by_iata(code);
	// next try icao
	if (idx < 0)
		idx = apt_get_idx_by_icao(code);
	// finally faa
	if (idx < 0)
		idx = apt_get_idx_by_faa(code);

	return idx;
}

function apt_binsearch(forwhat, where, valgetfn) {
	var low = 0;
	var high = where.length - 1;
	var highOnTop = (valgetfn(0) > valgetfn(high)) ? 1 : 0;
	while (low <= high) {
		var idx = parseInt((low + high) / 2);
		var currentElement = valgetfn(idx);
		if (!highOnTop) {
			if (currentElement < forwhat) {low=idx+1;continue;}
			if (currentElement > forwhat) {high=idx-1;continue;}
		} else {
			if (currentElement > forwhat) {low=idx+1;continue;}
			if (currentElement < forwhat) {high=idx-1;continue;}
		}
		return idx;
	}
	return -1;
}

function apt_get_desc(i) {
	var name = apt_get_name(i);
	var city = apt_get_city(i);
	var state = apt_get_state(i);
	var ctry = apt_get_country(i);
	
	var s = name;
	if (name.length > 0)
		s += ", ";
	s += city;
	if (city.length > 0)
		s += ", ";
	s += state;
	if (state.length > 0)
		s += ", ";
	s += ctry;
	return s;
}