'Ajax-registration of shelter inspection
@param r: the S3Request instance
@param attr: controller parameters'

def inspection_ajax(self, r, **attr):

    T = current.T
    db = current.db
    s3db = current.s3db
    s = r.body
    s.seek(0)
    try:
        data = json.load(s)
    except (ValueError, TypeError):
        r.error(400, current.ERROR.BAD_REQUEST)
    shelter_unit_id = data.get('u')
    if shelter_unit_id:
        error = False
        comments = data.get('c')
        update = False
        itable = s3db.cr_shelter_inspection
        query = (((itable.shelter_unit_id == shelter_unit_id) & (itable.date == current.request.utcnow.date())) & (itable.deleted != True))
        row = db(query).select(itable.id, limitby=(0, 1)).first()
        if row:
            update = True
            inspection_id = row.id
            row.update_record(comments=comments)
        else:
            inspection_id = itable.insert(shelter_unit_id=shelter_unit_id, comments=comments)
        if inspection_id:
            flag_ids = data.get('f')
            if update:
                query = (FS('inspection_id') == inspection_id)
                if flag_ids:
                    query &= (~ FS('flag_id').belongs(flag_ids))
                fresource = s3db.resource('cr_shelter_inspection_flag', filter=query)
                fresource.delete(cascade=True)
            if flag_ids:
                ftable = s3db.cr_shelter_inspection_flag
                if update:
                    query = ((ftable.inspection_id == inspection_id) & (ftable.deleted == False))
                    rows = db(query).select(ftable.flag_id)
                    new = (set(flag_ids) - set((row.flag_id for row in rows)))
                else:
                    new = set(flag_ids)
                ftable = s3db.cr_shelter_inspection_flag
                data = {'inspection_id': inspection_id}
                for flag_id in new:
                    data['flag_id'] = flag_id
                    success = ftable.insert(**data)
                    if (not success):
                        error = True
                        break
                    else:
                        record = Storage(data)
                        record['id'] = success
                        s3db.onaccept(ftable, record)
        else:
            error = True
        if error:
            db.rollback()
            output = {'a': s3_str(T('Error    registering    shelter    inspection'))}
        else:
            output = {'m': s3_str(T('Registration    successful'))}
    else:
        output = {'a': s3_str(T('No    shelter    unit    selected'))}
    return json.dumps(output)
