$(function(){
//autocomplite
                function split( val ) {
			return val.split( /,\s*/ );
		}
		function extractLast( term ) {
			return split( term ).pop();
		}

		$( "#subject" )
                // don't navigate away from the field on tab when selecting an item
			.bind( "keydown", function( event ) {
				if ( event.keyCode === $.ui.keyCode.TAB &&
						$( this ).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				minLength: 2,
			source: function( request, response ) {
                                var accentMap = [];
                                var normalize = function( term ) {
                                        var ret = "";
                                        for ( var i = 0; i < term.length; i++ ) {
                                                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
                                        }
                                        return ret;
                                };
                                //tylko 5 tematów można
                                //if(split(request.term).length == 5){return false;}
                                var matcher = new RegExp( $.ui.autocomplete.escapeRegex( extractLast( request.term ) ), "i" );
				response( $.grep( as['rows'], function( value ) {
					value = value.title || value.value || value;
					return matcher.test( value ) || matcher.test( normalize( value ) );
				}) );
                        },
			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
                                        //jeśli ilość odpowiedzi = 4
                                        if(terms.length <= 4){
                                            terms.push( ui.item );
                                        }
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
					return false;
				}
			})
                        .data( "autocomplete" )._renderItem = function( ul, item ) {
                            return $( "<li></li>" )
				.data( "item.autocomplete", item.title )
				.append( "<a>" + item.title + " (" + item.count_question + ")</a>" )
				.appendTo( ul );
                        };
});
