'Custom lookup method for site rows, does a left join with any
instance_types found.
Parameters key and fields are not used, but are kept for API
compatibility reasons.
@param values: the site IDs'

def custom_lookup_rows(self, key, values, fields=[]):

    db = current.db
    s3db = current.s3db
    stable = s3db.org_site
    count = len(values)
    if (count == 1):
        value = values[0]
        query = (stable.site_id == value)
        limitby = (0, 1)
    else:
        query = stable.site_id.belongs(values)
        limitby = (0, count)
    if self.show_link:
        rows = db(query).select(stable.instance_type, limitby=limitby)
        instance_types = []
        for row in rows:
            if (row.instance_type not in instance_types):
                instance_types.append(row.instance_type)
        fields = [stable.site_id, stable.instance_type, stable.name]
        left = []
        for instance_type in instance_types:
            table = s3db[instance_type]
            fields.append(table.id)
            left.append(table.on((table.site_id == stable.site_id)))
            if (instance_type == 'org_facility'):
                ltable = db.org_site_facility_type
                ttable = db.org_facility_type
                fields.append(ttable.name)
                left.append(ltable.on((ltable.site_id == stable.site_id)))
                left.append(ttable.on((ttable.id == ltable.facility_type_id)))
        rows = db(query).select(left=left, *fields)
    elif self.show_type:
        ttable = s3db.org_facility_type
        ltable = db.org_site_facility_type
        left = [ltable.on((ltable.site_id == stable.site_id)), ttable.on((ttable.id == ltable.facility_type_id))]
        rows = db(query).select(stable.site_id, stable.instance_type, stable.name, ttable.name, left=left, limitby=limitby)
    else:
        rows = db(query).select(stable.site_id, stable.name, limitby=limitby)
    self.queries += 1
    if self.translate:
        table = s3db.org_site_name
        query = ((table.deleted == False) & (table.language == current.session.s3.language))
        if (count == 1):
            query &= (table.site_id == value)
        else:
            query &= table.site_id.belongs(values)
        self.l10n = db(query).select(table.site_id, table.name_l10n, limitby=(0, count)).as_dict(key='site_id')
    return rows
