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.
Here's a more grammatical answer: 'im' is a contraction of 'in dem' (literally: in the) and 'dem' is the dative article (the) for neuter and masculine nouns. 'am' is 'an dem' and so forth.
I'm not sure of it myself but I've been using them like this: im for 'in the', or 'at the' if the 'at' in question is inside (im Restaurant). and am for 'on the' and 'at the' if the 'at' in question is outside (am Feld) Prepositions seem very confusing :(