
/**
 * AJAX Neighborhood Options
 *
 * Note: It's important to initialize this *after* the document is ready!
 *
 */
function NeighborhoodOptions(containerId, queryId, typeId, radiusId) {
	/* AJAX callback instance */
	var instance = this;
	
	this.lastQuery = null;
	
	/* Initialize members */
	if (containerId == null) {
		containerId = 'neighborhoodsAmenities';
	}
	this.container = $('#' + containerId);
	
	if (queryId == null) {
		this.query = $(':input[name="main_field"]');
	} else {
		this.query = $('#' + queryId);
	}
	
	if (typeId == null) {
		this.type = $(':input[name="search_type"]');
	} else {
		this.type = $('#' + typeId);
	}
	
	if (radiusId == null) {
		this.radius = $(':input[name="ssradius"]');
	} else {
		this.radius = $('#' + radiusId);
	}
	
	/* Bind to events */
	this.query.blur(function() {
		instance.refresh();
	});
	this.radius.change(function() {
		instance.refresh();
	});
	
	/* Invoke a refresh 
	 */
	this.refresh = function() {
		if (this.query.val().length > 0) {
			$.getJSON(NeighborhoodOptions.url + '?main_field=' + this.query.val() + 
				'&type=' + this.type.val() + '&ssradius=' + this.radius.val(), 
				'', instance.receive);
		} else {
			addShadowOverlay();
			this.clear();
		}
	}
	
	/* Receive JSON data and populate 'hoods
	 */
	this.receive = function(data) {
		if (data != null) {
			var html = '';
			$.each(data, function(index, result) {
				
				// Open <li>
				html += '<li id="n-' + index + '" class="xl ';
				 if (index % 3 == 0) {
					html += ' amenitiesLeftCol';
				 }
				 html += '" >';
				
				// Open <label>
				html += '<label for="neighborhood' + index + '" title="Click to require ' 
					+ result.NeighborhoodName + '">';
				
				// <input type="checkbox" />
				html += '<input type="checkbox" name="neighborhoods[]" value="' + result.NeighborhoodID +
					'" id="neigbhorhood' + index + '" title="Add ' + result.NeighborhoodName + '" />';
				
				// Label text
				html += result.NeighborhoodName;
				
				html += '</label></li>';
				
			});
			html += NeighborhoodOptions.textEntryHtml;
			instance.container.html(html);
            
            // Clear text box on focus
            $('#nhood').focus(function() {
                $(this).val('');
            });
            
		} else {
			//addShadowOverlay('There are no neighborhoods in the selected location');
			//addShadowOverlay();
			instance.clear();
		}
	}
	
	this.clear = function() {
		this.container.html('');
	}
}

/* Request URL */
NeighborhoodOptions.url = '/ajax/search/searchNeighborhoods.ajax.php';

/* HTML for text input */
NeighborhoodOptions.textEntryHtml = '<li id="n-textbox"><input type="text" id="nhood" title="Neighborhood Name(s)" name="user_entered_neighborhood" value="Find Your Neighborhood" /></li>';

