jQuery(function($){

function split(val) {
	return val.split(/,\s*/);
}
function extractLast(term) {
	return split(term).pop();
}

$("#search-input").one("focus", function () {
	if (this.value == "Enter keyword(s)") this.value = "";
}).autocomplete({
	source: function(request, response) {
		$.getJSON("kws/", {
			term: extractLast(request.term)
		}, response);
	},
	search: function() {
		// custom minLength
		var term = extractLast(this.value);
		if (term.length < 2) {
			return false;
		}
	},
	focus: function() {
		// prevent value inserted on focus
		return false;
	},
	select: function(event, ui) {
		var terms = split(this.value);
		// remove the current input
		terms.pop();
		// add the selected item
		terms.push(ui.item.value);
		// add placeholder to get the comma-and-space at the end
		terms.push("");
		this.value = terms.join(", ");
		return false;
	}
});

$("#color-mix td").click(function(){
	$("#search-color").val(this.id.replace("clr", ""));
});

$("#search").submit(function(){
	var kws = $("#search-input").val();
	var noKws = kws == "Enter keyword(s)" || kws.match(/^\s*$/);
	var res = !noKws || $("#search-color").val() != "";
	if (res) {
		$("#submitBtn").attr("disabled", "disabled");
		$("#search-input").val(noKws ? "" : kws.replace(/,+\s*$/, ''));
	}
	return res;
});

});
