$.ux.behavior("CitySearch", {
	initialize: function() {
		this.getResults(true);
	},
	showLoading: function() {
		this.element.html("");
		this.element.css("background", "url(/ui/images/legacy/ticker1.gif) no-repeat center center").css("height", "40px");
	},
	hideLoading: function() {
		this.element.css("background", "none").css("height", "auto");
	},
	getResults: function(isFirstLoad) {
		var self = this;
		this.showLoading();
		$.getJSON("/api/citysearch.aspx", { search: this.options.search, where: this.options.location, max: this.options.maxResults }, function(data) {
			self.options.location = data.location;
			if (isFirstLoad && data.ads.length == 0)
				self.element.parent().hide();
			else
				self.populateResults(data);
		});
	},
	changeLocation: function(location) {
		this.options.location = location;
		this.getResults();
	},
	populateResults: function(response) {
		this.hideLoading();
		this.element.template(this.options.jsTemplateId, { loc: response.location, results: response.ads });
	},
	onclick: $.delegate({
		'a.jsChangeLocation': function(element, event) {
			this.changeLocation(this.element.find("input").val());
		},
		'input': function(element, event) {
			element.select();
		}
	}),
	onkeydown: $.delegate({
		'input': function(element, event) {
			if (event.keyCode == 13) {
				this.changeLocation(element.val());
			}
		}
	})
}, {
	jsTemplateId: "tmpCitySearch",
	search: "",
	location: "",
	maxResults: 5
});
