Have a notebook and pen strapped to your side, or at least in a pocket. Also have another by the side of the bed to scribble in anything you want to note down while in bed.
The reason why you get ideas at strange times is basically because your normal day gets in the way of your subconscious mind. When your falling asleep or just waking is the most susceptable time for any ideas to come through. Many song writers have got hit music during the night or just on waking. If I remember rightly, Paul McCartney got one of his best sellers that way.
For me I get a lot in dream formate - it will be the full story right from the beginning to the last scene. If I'm lucky I can get things down pretty quickly, BUT whatever you do, do not get up from the bed or speak to anyone until the idea is on the page, or you'll forget.
Certain foods also stimulate the brain, as well as looking to the ceiling will help you remember, this also happens with smells as well.
It's well worth looking up basic psychology to find out how the memory and recall works, it helps no end when studying and writing.
PS the physical motion of writing things down puts into into a better place in the memory, it helps focus the ideas.