var CitySearchAjax = new Class({
	options: {
		name: "defaultname",
		resultAction: function(place) {
			// this is just the default resultAction; pass in your own!
			return new Element('li').setHTML(place.name);
		}
	},
	
	initialize: function(options) {
		if (!options.name) {
			alert("Error: the CitySearchAjax class must be initialized with at least the 'name' argument.");
			return false;
		}
		this.setOptions(options);
		this.searchForm = $(this.options.name + 'SearchForm');
		this.searchResults = $(this.options.name + 'SearchResults');
		this.searchSpinner = $(this.options.name + 'AjaxLoading');
		this.searchEffect = new Fx.Slide(this.searchResults, {duration: 500, wait: false});
		this.modifySearchForm(this);
	},
	
	modifySearchForm: function(me) {
		this.searchForm.adopt(new Element('input', {
			'type': 'hidden',
			'name': 'brand',
			'value': 'wundcitysearchajax'
		}));

		this.searchForm.addEvent('submit', function(e) {
			// 'this' now refers to the html form element, so use the 'me' pointer back to the class
			new Event(e).stop();
			var url = this.action + '?' + this.toQueryString();
			me.doSearch(url);
		});
	},
	
	doSearch: function(url) {
		this.searchResults.empty();
		this.searchEffect.hide();
		this.searchSpinner.addClass('ajax-loading');
		var me = this;
		
		var request = new Json.Remote(url, {
			onComplete: function(jsonObj) {
				// 'this' now refers to the request object, so use the 'me' pointer back to the class
				me.searchSpinner.removeClass('ajax-loading');
				try {
					me.jsonResultAction(jsonObj);
				}
				catch(e) {
					var jsonfailure = new Element('div', {'class': 'taC red'}).setHTML("Server Error: json could not be evaluated.");
					jsonfailure.injectInside(me.searchResults);
				}
				me.searchEffect.slideIn();
			},
			onFailure: function(transport) {
				// 'this' now refers to the request object, so use the 'me' pointer back to the class
				me.searchSpinner.removeClass('ajax-loading');
				var xhrfailure = new Element('div', {'class': 'taC red'}).setHTML("Server Error: ajax request failed.");
				xhrfailure.injectInside(me.searchResults);
				me.searchEffect.slideIn();
			}
		}).send();
	},
	
	jsonResultAction: function(jsonObj) {
		var me = this;
		var title = jsonObj.results[0];
		var places = jsonObj.results[1];
		if (!places || !places.length) {
			// no results error
			var noresults = new Element('div', {'class': 'taC red'}).setHTML(title);
			noresults.injectInside(this.searchResults);
			return;
		} else {
			// we have results, print the title first
			var titleElement = new Element('div', {'class': 'b'}).setHTML(title);
			titleElement.injectInside(this.searchResults);
		}
		var ul = new Element('ul');
		places.each(function(place) {
			var li = me.options.resultAction(place);
			if (li) {
				li.injectInside(ul);
			}
		});
		ul.injectInside(this.searchResults);
	}
});

CitySearchAjax.implement(new Options);
