'JSON search method for S3HumanResourceAutocompleteWidget and S3AddPersonWidget2
- full name search
- include Organisation & Job Role in the output'

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

    resource = r.resource
    response = current.response
    resource.add_filter(response.s3.filter)
    _vars = current.request.get_vars
    value = (_vars.term or _vars.value or _vars.q or None)
    if (not value):
        output = current.xml.json_message(False, 400, 'No    value    provided!')
        raise HTTP(400, body=output)
    value = s3_unicode(value).lower()
    if ('    ' in value):
        (value1, value2) = value.split('    ', 1)
        value2 = value2.strip()
        query = (FS('person_id$first_name').lower().like((value1 + '%')) & (FS('person_id$middle_name').lower().like((value2 + '%')) | FS('person_id$last_name').lower().like((value2 + '%'))))
    else:
        value = value.strip()
        query = ((FS('person_id$first_name').lower().like((value + '%')) | FS('person_id$middle_name').lower().like((value + '%'))) | FS('person_id$last_name').lower().like((value + '%')))
    resource.add_filter(query)
    settings = current.deployment_settings
    limit = int((_vars.limit or 0))
    MAX_SEARCH_RESULTS = settings.get_search_max_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:
        fields = ['id', 'person_id$first_name', 'person_id$middle_name', 'person_id$last_name', 'job_title_id$name']
        show_orgs = settings.get_hrm_show_organisation()
        if show_orgs:
            fields.append('organisation_id$name')
        name_format = settings.get_pr_name_format()
        test = (name_format % dict(first_name=1, middle_name=2, last_name=3))
        test = ''.join((ch for ch in test if (ch in ('1', '2', '3'))))
        if (test[:1] == '1'):
            orderby = 'pr_person.first_name'
        elif (test[:1] == '2'):
            orderby = 'pr_person.middle_name'
        else:
            orderby = 'pr_person.last_name'
        rows = resource.select(fields, start=0, limit=limit, orderby=orderby)['rows']
        output = []
        iappend = output.append
        for row in rows:
            name = Storage(first_name=row['pr_person.first_name'], middle_name=row['pr_person.middle_name'], last_name=row['pr_person.last_name'])
            name = s3_fullname(name)
            item = {'id': row['hrm_human_resource.id'], 'name': name}
            if show_orgs:
                item['org'] = row['org_organisation.name']
            job_title = row.get('hrm_job_title.name', None)
            if job_title:
                item['job'] = job_title
            iappend(item)
    response.headers['Content-Type'] = 'application/json'
    return json.dumps(output, separators=SEPARATORS)
