$(document).ready(function(){
	var neighborhoods = [];
	$('#neighborhoods li').each(function(){
		var neighborhood = {};
		
		neighborhood.agreementURL = $(this).find('a:first').attr('href');
		neighborhood.name = $.trim($(this).text());
		
		neighborhoods.push(neighborhood);
	});
	
	function buildResult(result, i){
		var $result = $('<li/>');
		var $name = $('<span/>').text(result.name);
		var $agreement = $('<a/>').attr('href', result.agreementURL).attr('target', '_blank').text('Download Clubhouse Rental Agreement');
		var $reservation = $('<a/>').attr('href', 'https://www.securedata-trans12.com/ap/eneighbors/index.php?page=10').attr('target', '_blank').text('Make a reservation online');
		
		$result.append($name).append($agreement).append($reservation);
		
		if(i % 2 == 0)
			$result.addClass('alt');
		
		return $result;
	}
	
	function buildErrorMessage(){
		var $message = $('<li/>').attr('id', 'no_results').text("Sorry, we were unable to find the neighborhood you searched for. Please check the spelling and try your search again.");
		
		return $message;
	}
	
	$('#search_form').data('neighborhoods', neighborhoods);
	$('#search_form').bind('submit', function(){ return false; }).bind('submit', function(){
		var neighborhoods = $(this).data('neighborhoods');
		var query = $(this).find('#query').val().toLowerCase();
		var results = [];
		var $results = $('#results');
		
		$results.empty();
		
		if(!query)
			return;
		
		$.each(neighborhoods, function(i, neighborhood){
			var name = neighborhood.name.toLowerCase();
			if(name.match(query)){
				results.push(neighborhood);
			}
		});
		
		$.each(results, function(i, result){
			$result = buildResult(result, i);
			$results.append($result);
		});
		
		if(!results.length){
			var $message = buildErrorMessage();
			$results.append($message);
		}
		
		return false;
	});
});

