$(function(){
	$("form.top-content-actions select").change(function(){
		this.selectedIndex == this.options.length-1 ? ($("input.ac-"+this.className+"-input").addClass("visible")) : ($("input.ac-"+this.className+"-input").removeClass("visible"))
	});
	$("form.top-content-actions select").blur(
		function(){
			var oSelect = this;
			setTimeout(
				function() {
					var input = $("input.ac-"+oSelect.className+"-input").get(0);
					if (input.focused) { return; }
					$(input).removeClass("visible");
					$(input).val("");
				},10
			);
		}
	);
	$("form.top-content-actions input.ac").focus(function() { this.focused = true; $(this).addClass("visible"); });
	$("form.top-content-actions input.ac").blur(
		function() {
			this.focused = false;
			var input = this;
			setTimeout(
				function() {
					$(input).removeClass("visible");
					$(input).val("");
					input.blur();
				},300
			);
		}
	);
	$("form.top-content-actions input.ac-city-input").autocomplete("/ajax/cities/", {
		formatItem: function (row, i, n, needle) {
			return row[0] + "<br /><small>" + row[1] + "</small>";
		}
	}).result(onResult);
	
	$("form.top-content-actions input.ac-developer-input").autocomplete("/ajax/developers/", {
		formatItem: function (row, i, n, needle) {
			return row[0];
		}
	}).result(onResult);
	
	function onResult(event,data,formatted) {
		var type = this.className.match(/ac-(.*?)-input/)[0].replace(/ac-(.*?)-input/,"$1");
		var sel = $("form.top-content-actions select."+type).get(0);
		var id = type == "city" ? 2 : 1;
		if ($("option[value='"+data[id]+"']",sel).length==0) {
			$("option:last-child",sel).before("<option value='"+data[id]+"'>"+data[0]+"</option>");
		}
		sel.selectedIndex = $("option[value='"+data[id]+"']",sel).get(0).index;
	}
});
