$(function() {
	$('#w').keyup(function(e) {
		var resultCount = 5;
		
		// handling up/down/escape requires results to be visible
		// handling enter/tab requires that AND a result to be selected
		if ((/27$|38$|40$/.test(e.keyCode) && $('#smart_search').is(':visible')) || (/^13$|^9$/.test(e.keyCode) && getCurrentResult())) {
			if (e.preventDefault)
				e.preventDefault();
			if (e.stopPropagation)
				e.stopPropagation();

			e.cancelBubble = true;
			e.returnValue = false;
		
			switch(e.keyCode) {
				case 38:	// up
					prevResult();
					break;
		
				case 40:	// down
					nextResult();
					break;
					
				case 13:	// return
					goCurrentResult();
					break;
				
				case 9:		// tab
				case 27:	//	escape
					$('#smart_search').hide();
					break;

			}
		} else if ($('#w').val()) {
			var values = $('#search_con').serialize();
			$.ajax({
				type: "GET",
				url: "/search/smart_search.php",
				dataType: "html",
				data: values,
				success: function(html) {
					if (html) {
						$('#smart_search').html(html);
						$('#smart_search').show().css({
							'zIndex': 990
						});
					}
					return false;
				}
			});
		} else {
			$('#smart_search').hide();
		}
	});
	
	$('#w').focus(function(e) {
		if ($(this).attr('value') == "search") {
			$(this).attr('value', '');
		}
		
		return false;
	});

	$('#w').blur(function (e) {
		if ($(this).attr('value') == undefined || $(this).attr('value') == "") {
			$(this).attr('value', 'search');
		}
		
		setTimeout(function () {
			$('#smart_search').hide();
		}, 300);
		
		return false;
	});
	
	$('#smart_search').blur(function() {
		$(this).hide();
		
		return false;
	});
});

function clearSearch() {
	$('#w').val('');
	return false;
}

function getCurrentResult() {
	var current = '';
	$('#smart_search li').each(function() {
		if ($(this).hasClass('current')) {
			current = $(this).attr('id');
		}
	});
	
	if (current)
		return current;
	else
		return false;
}

function goCurrentResult() {
	var current = getCurrentResult();
	if (current && $('#'+current).find('a:first').attr('href')) {
		location.href = $('#'+current).find('a:first').attr('href');
	}
	return false;
}

function nextResult() {
	var current = getCurrentResult();
	if (current) {
		if ($('#'+current).next().attr('id')) {
			$('#'+current).removeClass('current');
			if (!$('#'+current).next().hasClass('not_linked')) {
				$('#'+current).next().addClass('current');
			} else {
				$('#'+current).next().next().addClass('current');
			}
		}
	} else {
		$('#smart_search li:first').addClass('current');
	}
}

function prevResult() {
	var current = getCurrentResult();
	if (current) {
		if ($('#'+current).prev().attr('id')) {
			$('#'+current).removeClass('current');
			if (!$('#'+current).prev().hasClass('not_linked')) {
				$('#'+current).prev().addClass('current');
			} else {
				$('#'+current).prev().prev().addClass('current');
			}
		}
	} else {
		$('#smart_search li:first').addClass('current');
	}
}
