This can be done with trigger and procedures I think but it won't be easy.
You can't use a foreign key based on some condition.
A trigger in which you use a procedure with dynamic statements maybe can do the trick.
Haven't tried this yet, if a have some time I'll try next week.