what is the difference between them? what's the rule for when to use which one?
Sometimes they can be used interchangeably, a lot of the time they are used with idiomatic expressions and prepositional phrases. Im: in the, or at Am: at, at the, on the 'Beim' is another that is even more flexible. Your best guess is usually correct or close enough to be understood until you hear them often enough to use them correctly by nature. I'm not sure if there is a rule, a native speaker will more than likely answer more diligently.