'JSON search method for S3AutocompleteWidget
@param r: the S3Request
@param attr: request attributes'

@staticmethod
def pe_search_ac(r, **attr):

    get_vars = current.request.get_vars
    value = (get_vars.term or get_vars.value or get_vars.q or None)
    if (not value):
        output = current.xml.json_message(False, 400, 'No    search    term    specified')
        raise HTTP(400, body=output)
    value = s3_unicode(value).lower()
    limit = int((get_vars.limit or 0))
    types = get_vars.get('types')
    if types:
        types = types.split(',')
    else:
        types = ('pr_person', 'pr_group')
    response = current.response
    resource = r.resource
    table = resource.table
    table.pe_id.represent = pr_PersonEntityRepresent(show_label=False)
    default_filter = response.s3.filter
    items = []
    if ('pr_person' in types):
        entity = 'pe_id:pr_person'
        first_name = FS(('%s.first_name' % entity)).lower()
        middle_name = FS(('%s.middle_name' % entity)).lower()
        last_name = FS(('%s.last_name' % entity)).lower()
        if ('    ' in value):
            (first, last) = value.split('    ', 1)
            first = ('%s%%' % first)
            last = ('%s%%' % last.strip())
            query = (first_name.like(first) & (middle_name.like(last) | last_name.like(last)))
        else:
            value = ('%s%%' % value.strip())
            query = ((first_name.like(value) | middle_name.like(value)) | last_name.like(value))
        resource.clear_query()
        resource.add_filter(default_filter)
        resource.add_filter(query)
        data = resource.select(fields=['pe_id'], limit=limit, raw_data=True, represent=True, show_links=False)
        items.extend(data.rows)
    if ('pr_group' in types):
        entity = 'pe_id:pr_group'
        field = FS(('%s.name' % entity)).lower()
        query = field.like(('%%%s%%' % value))
        resource.clear_query()
        resource.add_filter(default_filter)
        resource.add_filter(query)
        data = resource.select(fields=['pe_id'], limit=limit, raw_data=True, represent=True, show_links=False)
        items.extend(data.rows)
    if ('org_organisation' in types):
        entity = 'pe_id:org_organisation'
        field = FS(('%s.name' % entity)).lower()
        query = field.like(('%%%s%%' % value))
        resource.clear_query()
        resource.add_filter(default_filter)
        resource.add_filter(query)
        data = resource.select(fields=['pe_id'], limit=limit, raw_data=True, represent=True, show_links=False)
        items.extend(data.rows)
    result = []
    append = result.append
    for item in items:
        raw = item['_row']
        append({'id': raw['pr_pentity.pe_id'], 'name': item['pr_pentity.pe_id']})
    output = json.dumps(result, separators=SEPARATORS)
    response.headers['Content-Type'] = 'application/json'
    return output
