anchor.diff:              {error, bad_encoding}
       end.
   
  -define_anon_js(JS, #state{ctx=Ctx, anon_funs=AnonFuns, next_funid=NextFunId}=State) ->
  -    Hash = erlang:phash2(JS),
  -    case proplists:get_value(Hash, AnonFuns) of
  -        undefined ->
  -            FunId = case NextFunId > ?MAX_ANON_FUNS of
  -                        true ->
  -                            1;
  -                        false ->
  -                            NextFunId
  -                    end,
  -            FunName = list_to_binary("riakAnon" ++ integer_to_list(FunId)),
  -            case js:define(Ctx, list_to_binary([<<"var ">>, FunName, <<"=">>, JS, <<";">>])) of
  -                ok ->
  -                    {ok, FunName, State#state{anon_funs=[{Hash, FunName}|AnonFuns], next_funid=NextFunId + 1}};
  -                Error ->
  -                    error_logger:warning_msg("Error defining anonymous Javascript function: ~p~n", [Error]),
  -                    {Error, undefined, State}
  -            end;
  -        FunName ->
  -            {ok, FunName, State}
  +define_anon_js(JS, Args) ->
  +    try
  +        ArgList = build_arg_list(Args, []),
  +        iolist_to_binary([JS, <<"(">>, ArgList, <<");">>])
  +    catch
  +        exit: {ucs, {bad_utf8_character_code}} ->
  +            error_logger:error_msg("Error JSON encoding arguments: ~p~n", [Args]),
  +            {error, bad_encoding};
  +        exit: {json_encode, _} ->
  +            {error, bad_json};
  +        throw:invalid_utf8 ->
  +            {error, bad_encoding}
       end.
   
   new_context(ThreadStack, HeapSize) ->
  
positive.code: 
  %% Internal functions
  define_invoke_anon_js(JS, Args, #state{ctx=Ctx}=State) ->
      case define_anon_js(JS, State) of
          {ok, FunName, NewState} ->
              case invoke_js(Ctx, FunName, Args) of
                  {ok, R} ->
                      {{ok, R}, NewState};
                  Error ->
                      {Error, State}
              end;
          {Error, undefined, NewState} ->
              {Error, NewState}
      end.
  
  invoke_js(Ctx, Js, Args) ->
  
negative.code: 
  -define(SERVER, ?MODULE).
  
  -record(state, {manager, pool, ctx, in_batch=false}).
  
  start_link(Manager, PoolName) ->
      gen_server:start_link(?MODULE, [Manager, PoolName], []).
  