var suggestSelector = '';

function suggestInit(selector)
{
	suggestSelector = selector;
	$(selector).after('<div id="suggestContainer"></div>');
	$(selector).bind('input', function () {
		var query = $(selector).val();
		$('#suggestContainer').html('');
		$.ajax({
			url: "/json/search?query=" + query,
			context: document.body
		}).done(function (data) {
			res = data.suggestions;
			newHtml = '';
			$('#suggestContainer').html('').show();
			for (var i = 0; i < res.length; i++) {
				newHtml += '<div><a href="' + res[i].data + '">' + res[i].value + '</a></div>';
			}
			$('#suggestContainer').html(newHtml);
		}).fail(function (jqXHR, textStatus) {
			alert("Request failed: " + textStatus);
		});
	}).bind('keydown', function (event) {
		suggestKeyPress(event.which);
	}).bind('focus', function(){if($(selector).val())$('#suggestContainer').show();});
	$(selector).parent().bind('blur', function(){$('#suggestContainer').hide();});
	$('#suggestContainer').hide();
}

function suggestKeyPress(key)
{
	switch (key) {
		case 27:
				//ESCAPE
				$('#suggestContainer').hide();
			break
		case 13:
				//ENTER
				if ( $('div.hover','#suggestContainer').length > 0 ) {
					link = $('a', $('div.hover','#suggestContainer')).attr('href');
				} else {
					searchAdderess();
				}
				window.location.href = link;
			break
		case 38:
				//UP
				if ( $('div.hover','#suggestContainer').length > 0 ) {
					if ($('div.hover','#suggestContainer').prev().length > 0) {
						$('div.hover','#suggestContainer').removeClass('hover').prev().addClass('hover');
					} else {
						$('div','#suggestContainer').removeClass('hover').last().addClass('hover');
					}
				} else {
					$('div','#suggestContainer').last().addClass('hover');
				}
			break
		case 40:
				//DOWN
				if ( $('div.hover','#suggestContainer').length > 0 ) {
					if ($('div.hover','#suggestContainer').next().length > 0) {
						$('div.hover','#suggestContainer').removeClass('hover').next().addClass('hover');
					} else {
						$('div','#suggestContainer').removeClass('hover').first().addClass('hover');
					}
				} else {
					$('div','#suggestContainer').first().addClass('hover');
				}
			break
		default :
			if($(suggestSelector).val()) {
				$('#suggestContainer').show();
			}
	}

}
