Which of the pilots flies when it gets dangerous? Who flies when it gets dangerous ?

In other words: Which pilot takes control of a passenger aircraft as Pilot Flying (PF) in an emergency (aircraft upset, loss of control, mechanical failure, etc.) and why ?


the highest-ranking pilot present in the cockpit given his experience
the SIC (second in command), for the reasons quoted below
whoever was PF when the incident began continues flying
or no specific rules, the pilots must make a joint decision



  Just beware that either pilot may be at the controls during a
  particular incident. In fact, while protocols are different [from] carrier to
  carrier, it's not unusual during emergencies or other abnormal
  situations, for the captain to delegate hands-on flying duties to the
  copilot, so that the captain can concentrate on communications,
  troubleshooting, coordinating the checklists, etc. (source)


Case in point:
In the AF447 crash, the captain was not in the cockpit when the incident began. When returning to the cockpit, he did not take over control but sat down behind the 2 First Officers.



Please mention in your answer
- which person (if any) is designated by the regulations, airline rules and best practices
- for what reason
- and whether these rules/recommendations have often been not followed in crashes
In the end it's all up to the Captain.  If the FO is PF, which with most airlines alternates with each leg of a block, and something exciting happens, the capt may let the FO continue flying if the capt feels the FO has things under control.  Or the capt may say "I have control" and take over.  Depends.  

The Pilot In Command is pilot in command.  He/she commands, but with modern CRM rules, there is expected to be some mutual consultation and decision making, so the command authority has to take all that into account.

AF447 was an unusual situation where the capt didn't realize early enough what a clusterfark the two FOs sitting in the front seats had gotten themselves into, who were both mentally overloaded into a tunnel vision state, and especially the right seater, who appeared to lack basic fully internalized flying skills, sitting in panic mode with the stick full aft for almost the entire ride down.