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

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

    response = current.response
    resource = r.resource
    settings = current.deployment_settings
    resource.add_filter(response.s3.filter)
    _vars = current.request.get_vars
    value = (_vars.term or _vars.value or _vars.q or None)
    value = s3_unicode(value).lower().strip()
    if (not value):
        output = current.xml.json_message(False, 400, 'Missing    option!    Require    value')
        raise HTTP(400, body=output)
    query = FS('name').lower().like((value + '%'))
    extra_fields = settings.get_org_site_autocomplete_fields()
    for field in extra_fields:
        if ('addr_street' in field):
            query |= FS(field).lower().like((('%' + value) + '%'))
        else:
            query |= FS(field).lower().like((value + '%'))
    resource.add_filter(query)
    MAX_SEARCH_RESULTS = settings.get_search_max_results()
    limit = int((_vars.limit or MAX_SEARCH_RESULTS))
    if (((not limit) or (limit > MAX_SEARCH_RESULTS)) and (resource.count() > MAX_SEARCH_RESULTS)):
        output = [dict(label=str((current.T('There    are    more    than    %(max)s    results,    please    input    more    characters.') % dict(max=MAX_SEARCH_RESULTS))))]
    else:
        from s3.s3widgets import set_match_strings
        s3db = current.s3db
        fields = ['name', 'site_id']
        fields += extra_fields
        rows = resource.select(fields, start=0, limit=limit, orderby='name', as_rows=True)
        output = []
        append = output.append
        for row in rows:
            _row = row.get('org_site', row)
            record = {'id': _row.site_id, 'name': _row.name}
            org = row.get('org_organisation.name', None)
            if org:
                record['org'] = org
            L1 = row.get('gis_location.L1', None)
            if L1:
                record['L1'] = L1
            L2 = row.get('gis_location.L2', None)
            if L2:
                record['L2'] = L2
            L3 = row.get('gis_location.L3', None)
            if L3:
                record['L3'] = L3
            L4 = row.get('gis_location.L4', None)
            if L4:
                record['L4'] = L4
            addr_street = row.get('gis_location.addr_street', None)
            if addr_street:
                record['addr'] = addr_street
            set_match_strings(record, value)
            append(record)
    response.headers['Content-Type'] = 'application/json'
    return json.dumps(output, separators=SEPARATORS)
