Historically the 12-hour clock originated with the Sumerians, although their hours' lengths varied seasonally with the time of sunrise and sunset.
A.M. is an abbreviation of ante meridiem, Latin for "before noon". However, 9 a.m. does not mean 9 hours before noon, but 9 o'clock whilst being before noon. This is used to define hours of the day: "The meeting starts at 9 a.m." The opposite of A.M. is P.M., which is an abbreviation of post meridiem, Latin for "after noon".
The topic of whether 12:00 a.m. and 12:00 p.m. each correspond to noon or midnight is a source of great confusion and pedantic argument. The convention is that midnight is 12:00 a.m. and noon is 12:00 p.m. Often, it is better just to say "noon" or "midnight", and avoid the issue completely, making the cycle of hours as follows:
Another way of resolving the problem is to avoid referring to these tricky times entirely, and refer to times that are "just off" and therefore unambiguous, such as 11:59 p.m., or 12:01 a.m. Resolving this issue was one of the reasons for the creation of the 24-hour clock, sometimes called military time in the USA.