$(document).ready(function(){
	var aj,strPreviousSearch;
	aj = strPreviousSearch = null;
	// Display a div under the correct field
	$('#divDropDown ul li').live('click', function() {
		$('#strLocation').val($(this).text());
		$('#divDropDown').css('display', 'none');
	});

	$('#strLocation').bind('blur', function(){
		if (!$('#divDropDown').data('hover')) {
			$('#divDropDown').css('display', 'none');
		}
	});
	
	$('#divDropDown').hover(
		function() { $.data(this, 'hover', true); },
		function() { $.data(this, 'hover', false); }).data('hover', false);
	
	var showSelector = function() {
		$('#divDropDown').css('display', 'block');
		var oOff = $('#strLocation').offset();
		var intDivLeft = oOff.left;
		var intDivTop = oOff.top + $('#strLocation').outerHeight();
		//$('#divDropDown').width($('#strLocation').width());
		$('#divDropDown').width(200);
		$('#divDropDown').offset({top: intDivTop, left: intDivLeft});
	}
	
	$('#strLocation').bind('keyup', function (e) {
		var strValue = $('#strLocation').val();
		
		if (strValue.length > 2) {
			
			if (strValue !== strPreviousSearch) {
				strPreviousSearch = strValue;
				// Do the ajax search
				if (aj != null) {
					aj.abort();
				}
				aj = $.post('/ajax/search/locations/name-search/', {strSearch: strValue}, function(data){
					showSelector();
					if (data.results.length > 0) {
						$('#divDropDown').css('display', 'block');
						$('#divDropDown ul').css('display', 'block');
						$('#divDropDown p').css('display', 'none');
						$('#divDropDown ul').empty();
						$(data.results).each(function(i,item){
							$('#divDropDown ul').append("<li>" + item.name +  "</li>");
						});
					} else {
						$('#divDropDown').css('display', 'none');
					}
	
				}, 'json');
			}
			

		}
	})
});
