var _keyTimer;
var _sboxExists = false; // Suggestion box exists? treu/false
var _sboxFocus = false;
var _propNameFocus = false;
	
function getPropNames(baseStr){
	baseStr = escape(baseStr);
	
	var _data = $.ajax({
		type: "GET",
		url: "/Scripts/ajax/propName.php?name=" + baseStr,
		cache: false,
		async: false,
		dataType: "html"
	});
	
	_data = _data.responseText.split('|');
	return _data;
}

function renderPropNames(baseStr){
	var _results = getPropNames(baseStr);
	var _tHtml = '';
	
	if(_results[0] != ''){
		for(var i in _results){
			_tHtml = _tHtml + '<option value="'+_results[i]+'">'+_results[i]+'</option>';
		}
		
		if(!_sboxExists){
			_tWidth = $('#propName').width();
			
			$('#propName').after('<select size="10" id="propNameSuggestions"></select>');
			
			if($.browser.mozilla){
				$('#propNameSuggestions').width(_tWidth + 7);
				$('#propNameSuggestions').css("margin-left","-1px");
				$('#propNameSuggestions').css("margin-top","-2px");
			}
			else if($.browser.msie){
				$('#propNameSuggestions').width(_tWidth + 8);
				$('#propNameSuggestions').css("margin-left","-1px");
				$('#propNameSuggestions').css("margin-top","-2px");
			}
			
			_sboxExists = true;
		}
		var _sbox = $('#propNameSuggestions');
		_sbox.html(_tHtml);
		
		$('#propNameSuggestions').focus(function(){
			_sboxFocus = true;
		});
		
		/*$('#propNameSuggestions').blur(function(){
			_sboxFocus = false;
		});*/
		
		$('#propNameSuggestions').click(function(){
			$('#propName').val($(this).val());
			hideSbox();
		});
		
		$('#propNameSuggestions').keydown(function(e){
			if(e.which == 13){
				$('#propName').val($(this).val());
				hideSbox();
			}
		});
	}
	else{
		hideSbox();
	}
}

function hideSbox(){
	if(_sboxExists){
		$('#propNameSuggestions').remove();
		_sboxExists = false;
		setTimeout("blurSbox()",50);
		$('#propName').focus();
	}
}

function blurSbox(){
	_sboxFocus = false;
}

$(document).ready(function(){
			   
	$('#propName').keydown(function(e){
		if( e.which != 9 && e.which != 13 && !(_sboxExists == true && e.which == 40) ){
			var _propName = $(this).val();
			clearTimeout(_keyTimer);
			if(_propName.length >= 3){
				// Fetch the results after a short delay. This prevents the script
				// from requesting results from the server for every keystroke
				_keyTimer = setTimeout("renderPropNames('"+_propName+"')",250);
			}
			else{
				hideSbox();
			}
		}
		
	});
	
	$('#propName').keydown(function(e){
		if(e.which == 40){
			$('#propNameSuggestions').focus();	
		}
	});
	
});