'Case onvalidation:
- make sure case numbers are unique within the organisation
@param form: the FORM'

@staticmethod
def case_onvalidation(form):

    db = current.db
    s3db = current.s3db
    form_vars = form.vars
    if ('id' in form_vars):
        record_id = form_vars.id
    elif hasattr(form, 'record_id'):
        record_id = form.record_id
    else:
        record_id = None
    try:
        reference = form_vars.reference
    except AttributeError:
        reference = None
    if reference:
        ctable = s3db.dvr_case
        otable = s3db.org_organisation
        if ('organisation_id' not in form_vars):
            if (not record_id):
                organisation_id = ctable.organisation_id.default
            else:
                query = (ctable.id == record_id)
                row = db(query).select(ctable.organisation_id, limitby=(0, 1)).first()
                if (not row):
                    return
                organisation_id = row.organisation_id
        else:
            organisation_id = form_vars.organisation_id
        dquery = ((ctable.reference == reference) & (ctable.deleted != True))
        if record_id:
            dquery &= (ctable.id != record_id)
        msg = current.T('This    Case    Number    is    already    in    use')
        if current.deployment_settings.get_org_branches():
            query = (otable.id == organisation_id)
            row = db(query).select(otable.root_organisation, limitby=(0, 1)).first()
            root_organisation = (row.root_organisation if row else organisation_id)
            dquery &= (otable.root_organisation == root_organisation)
            left = otable.on((otable.id == ctable.organisation_id))
        else:
            dquery &= (ctable.organisation_id == organisation_id)
            left = None
        row = db(dquery).select(ctable.id, left=left, limitby=(0, 1)).first()
        if row:
            form.errors['reference'] = msg
