
var ajaxRunning = false;
var ajaxGeo = false;

$(document).ready(function(){

	
	
	$('#test_city div.box:not(.unselectable)').live('mouseover',function(){
		$('#test_city div.selected').removeClass('selected');
		$(this).addClass('selected');
		});
		
	});
	
function checkCity(event,geonameid)
{
	if(typeof(geonameid)!=undefined)
	{
		$('#form_geonameid').val('');
	}
	else
	{
		geonameid = false;
	}
	
	var badCodes = [9,16,17,18,20,27,33,34,35,36,37,39,45,112,113,114,115,116,117,118,119,120,121,122,123];

	if($.inArray(event.keyCode,badCodes)>=0)
		return false;

	if(event.keyCode == 40)
	{
		el =$('#test_city div.box.selected'); 
		el.removeClass('selected');
		if(el.next(':not(.unselectable)').length == 0)
			el = $('#test_city div.box:not(.unselectable):first');
		else
			el = el.next(':not(.unselectable)');
		el.addClass('selected');
		$('#test_city').scrollTop($('#test_city').scrollTop()+$(el).position().top-(($('#test_city').height()-$(el).outerHeight())/2));
		return false;
	}
	if(event.keyCode == 38)
	{
		el =$('#test_city div.box.selected'); 
		el.removeClass('selected');
		if(el.prev(':not(.unselectable)').length == 0)
			el = $('#test_city div.box:not(.unselectable):last');
		else
			el = el.prev(':not(.unselectable)');
		el.addClass('selected');
		$('#test_city').scrollTop($('#test_city').scrollTop()+$(el).position().top-(($('#test_city').height()-$(el).outerHeight())/2));
		return false;
	}
	if(event.keyCode == 13)
	{
		event.preventDefault();
		return false;
	}

	if($.trim($('#form_city').val()) == '')
	{
		return;
	}
	
	ajaxGeo = $.ajax({
		type: "POST",
		url: "../include/geonames.feedback.php",
		dataType: 'html',
		data: {
			action: "FIND",
			city : $('#form_city').val()
		},
		beforeSend: function(){
			if (ajaxRunning) 
				ajaxGeo.abort();
			ajaxRunning = true;
			$('#test_city').empty().append('<div class="box boxI unselectable" style="font-style;italic">Running</div>');
		},
		success: function(data){
			ajaxRunning = false;
			$('#test_city').empty().append(data);
			if(!geonameid)
				$('#test_city div:not(.unselectable):first').addClass('selected');
			else
			{
				$('#geo_'+geonameid).addClass('selected');
				$('#test_city').scrollTop($('#test_city').scrollTop()+$('#geo_'+geonameid).position().top-(($('#test_city').height()-$('#geo_'+geonameid).outerHeight())/2));
			}
			$('#test_city').children('div').bind('click',function(){
				selectCity();
				});
			return false;
		}
		
	});

	
	return false;

	
}

function goCity(event)
{

	if(event.keyCode == 13)
	{
		event.preventDefault();
		selectCity();
		return false;
	}
}
function selectCity()
{
	var val,id,el,
	val = '';
	id='';
	el = $('#test_city div.selected div:first');
	if(el.length==0)
		el = false;
	else
	{
		val = el.text();
		id = $('#test_city div.selected').attr('id').substr(4);
	}
	$('input#form_city').val(val);
	$('input#form_geonameid').val(id);
	$('#test_city').empty();
	$('input#form_city').trigger('blur');
}