I'm new to German and I get a bit confused about when it's "dem" or "im" or "den" rather than "in der" or "in dem" and so on.
In many languages, prepositions and articles are sometimes contracted.
- an + dem + noun → am + noun
- in + dem + noun → im + noun
- zu + dem + noun → zum + noun
- zu + der + noun → zur + noun
Contractions that may occur in informal speech:
- vor + dem + noun → vorm + noun
As for choosing between different cases:
If the case comes after a verb, you have to know what case the verb demands.
This corresponds to the knowledge of deciding if the correct English sentence is "I touch you." or "I touch to you." and very often, the construction with "to" corresponds to dative in German and without it to accusative in German. In the light of the next phrase it can be more helpful to think of the action being done "for" someone when the dative is used.
For prepositions again, you should learn what case they demand, but an important rule is: If the meaning is where something is, then the object has to take the dative, if the meaning is where it moves to, then the object has to take the accusative. Note that this deviates from the correspondence with "to" in the previous paragraph.
It would be good to ask a more specific question if you want to know more.
In written German, use only the contractions listed by Phira.
in patterned speech
Etwas zum Besten geben, zur Schule gehen
Hans ist am größten.
If the noun to which the preposition is related has already been introduced or needs for other reasons not to be emphasized (e.g., if it is not important which one it is), it is better to use a contraction with a less "emphasizing" character:
Ich bin zum Bäcker gegangen.
An dem Tag habe ich schon etwas vor.
If you are in doubt, I would advise not using contractions, as they tend to sound a little "uncouth" if overused.