'Apply method.
@param r: the S3Request
@param attr: controller options for this request'

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

    if (not r.record):
        r.error(404, current.ERROR.BAD_RECORD)
    alert_id = r.id
    authorised = current.auth.s3_has_permission('update', 'cap_alert', record_id=alert_id)
    if (not authorised):
        r.unauthorised()
    T = current.T
    s3db = current.s3db
    response = current.response
    itable = s3db.cap_info
    row = current.db((itable.alert_id == alert_id)).select(itable.event_type_id, limitby=(0, 1)).first()
    area_filter = ((FS('is_template') == True) & (FS('event_type_id') == row.event_type_id))
    if (r.http == 'POST'):
        added = 0
        post_vars = r.post_vars
        if all([(n in post_vars) for n in ('assign', 'selected', 'mode')]):
            selected = post_vars.selected
            if selected:
                selected = selected.split(',')
            else:
                selected = []
            if (post_vars.mode == 'Exclusive'):
                if ('filterURL' in post_vars):
                    filters = S3URLQuery.parse_url(post_vars.ajaxURL)
                else:
                    filters = None
                query = (area_filter & (~ FS('id').belongs(selected)))
                aresource = s3db.resource('cap_area', filter=query, vars=filters)
                rows = aresource.select(['id'], as_rows=True)
                selected = [str(row.id) for row in rows]
            for area_id in selected:
                area_id = int(area_id.strip())
                add_area_from_template(area_id, alert_id)
                added += 1
        if (added == 1):
            confirm_text = T('1    area    assigned')
        elif (added > 1):
            confirm_text = (T('%(number)s    areas    assigned') % {'number': added})
        current.session.confirmation = confirm_text
        if (added > 0):
            redirect(URL(args=[r.id, 'area'], vars={}))
        else:
            redirect(URL(args=r.args, vars={}))
    elif (r.http == 'GET'):
        filter_widgets = []
        list_fields = ['id', 'name', 'event_type_id']
        aresource = s3db.resource('cap_area', filter=area_filter)
        totalrows = aresource.count()
        get_vars = r.get_vars
        if ('pageLength' in get_vars):
            display_length = get_vars['pageLength']
            if (display_length == 'None'):
                display_length = None
            else:
                display_length = int(display_length)
        else:
            display_length = 25
        if display_length:
            limit = (4 * display_length)
        else:
            limit = None
        (query, orderby, left) = aresource.datatable_filter(list_fields, get_vars)
        aresource.add_filter(query)
        data = aresource.select(list_fields, start=0, limit=limit, orderby=orderby, left=left, count=True, represent=True)
        filteredrows = data.numrows
        dt = S3DataTable(data.rfields, data.rows)
        dt_id = 'datatable'
        dt_bulk_actions = [(T('Assign'), 'assign')]
        if (r.representation == 'html'):
            aresource.configure(deletable=False)
            profile_url = URL(c='cap', f='area', args=['[id]', 'read'])
            S3CRUD.action_buttons(r, deletable=False, read_url=profile_url, update_url=profile_url)
            response.s3.no_formats = True
            items = dt.html(totalrows, filteredrows, dt_id, dt_ajax_url=URL(args=r.args, extension='aadata', vars={}), dt_bulk_actions=dt_bulk_actions, dt_pageLength=display_length, dt_pagination='true', dt_searching='false')
            if filter_widgets:
                get_vars = aresource.crud._remove_filters(r.get_vars)
                filter_submit_url = r.url(vars=get_vars)
                filter_ajax_url = URL(f='cap_area', args=['filter.options'], vars={})
                get_config = aresource.get_config
                filter_clear = get_config('filter_clear', True)
                filter_formstyle = get_config('filter_formstyle', None)
                filter_submit = get_config('filter_submit', True)
                filter_form = S3FilterForm(filter_widgets, clear=filter_clear, formstyle=filter_formstyle, submit=filter_submit, ajax=True, url=filter_submit_url, ajaxurl=filter_ajax_url, _class='filter-form', _id='datatable-filter-form')
                fresource = s3db.resource('cap_area')
                ff = filter_form.html(fresource, r.get_vars, target='datatable')
            else:
                ff = ''
            output = {'items': items, 'title': T('Add    Areas'), 'list_filter_form': ff}
            response.view = 'list_filter.html'
            return output
        elif (r.representation == 'aadata'):
            if ('draw' in get_vars):
                echo = int(get_vars.draw)
            else:
                echo = None
            items = dt.json(totalrows, filteredrows, dt_id, echo, dt_bulk_actions=dt_bulk_actions)
            response.headers['Content-Type'] = 'application/json'
            return items
        else:
            r.error(415, current.ERROR.BAD_FORMAT)
    else:
        r.error(405, current.ERROR.BAD_METHOD)
