var running = null;
var source = null;
var list = null;
var cleaner = null;

function isIe()
{
    var msk = /MSIE (\d+\.\d+);/;
    if( msk.test(navigator.userAgent) ) {
        return true;
    } 
    return false;
}   

function makeList()
{
	pos = getPageCoords( source );
	list = document.createElement( "UL" );
	list.style.display = "block";
	list.style.position = "absolute";
	
	if( isIe() ) {
		list.style.left = (pos.x) + "px";
		list.style.top = (pos.y + 17) + "px";
		list.style.width = (source.offsetWidth - 1) + "px";
	} else {
		list.style.left = (pos.x - 1) + "px";
		list.style.top = (pos.y + 16) + "px";
		list.style.width = (source.offsetWidth - 2) + "px";
	}
	list.id = "athletesList";
	document.body.appendChild( list );
}

function onApres(id, ok, response)
{
	if( ok ) {
		if( response.length > 0 ) {
			if( list == null )
				makeList();
				
			var olds = list.getElementsByTagName( "LI" );
			
			while( olds.length ) {
				if( list == null ) return;
				list.removeChild( olds[ 0 ] );
				olds = list.getElementsByTagName( "LI" );
			}
	
			for( var j = 0; j < response.length; j ++ ) {
				var item = document.createElement( "LI" );
				item.innerHTML = "<A href=\"/" + response[ j ].id + ",Athletes.html\">" + response[ j ].name + "</A>";
				list.appendChild( item );
				if( j >= 6 ) {
					var last = document.createElement( "LI" );
					last.innerHTML = "<A href=\"javascript:apsearch();\">...</a>";
					list.appendChild( last );
					break;
				}
			}
		} else if( list != null ) {
			document.body.removeChild( list );
			list = null;
		}
	} else if( list != null ) {
		document.body.removeChild( list );
		list = null;
	}
	
	running = null;
}

function apsearch()
{
	var f = document.forms[ "atl" ];
	if( f ) {
		f.submit();
	}
}

function apres(field)
{
	var q = new String( field.value );
	if( (q.length > 1) && (running == null) ) {
		source = field;
		running = new Question( "qa", "/php/athletes.php", "q=" + q, onApres );
		running.ask();
	}
	
	if( cleaner != null ) {
		window.clearTimeout( cleaner );
		cleaner = null;
	}
}

function finalApext()
{
	if( running != null )
		running = null;
	
	source = null;
	
	if( list != null )
		document.body.removeChild( list );
	
	list = null;
	cleaner = null;
}

function apext(field)
{
	if( cleaner != null ) return;
	if( list == null ) return;
	if( window == null ) return;
	cleaner = window.setTimeout( "finalApext()", 1200 );
}
