Just a brief slice of the pie, while in basic this is drilled into your head so you dont mess up, they also tell you "when in doubt, whip it out" because its better to look like a fool saluting someone that isnt an officer (it happens a lot especially if you are unfamiliar with the rank structure of other branches. such as the navy, their petty officer rank is easily confused for a full bird colonel if youre new...I know cause it happened to me...) you can salute any person in uniform, its a formal greeting, like shaking a hand but more suitable in a military setting. Lots of information in the link provided so feel free to check it out and read up it.
http://usmilitary.about.com/cs/generalinfo/a/salute.htm
Persons Entitled to a Salute
•The President of the United States (Commander-in-Chief)
•Commissioned Officers and Warrant Officers
•Any Medal of Honor Recipient
•Officers of Friendly Foreign Countries
A salute is also rendered
•When the United States National Anthem, "To the Color," "Hail to the Chief," or foreign national anthems are played.
•To uncased National Color outdoors.
•On ceremonial occasions (such as Change of Command, and Military Parades).
•At reveille and retreat ceremonies, during the raising or lowering of the flag.
•During the sounding of honors.
•When the Pledge of Allegiance to the U.S. flag is being recited outdoors.
•When turning over control of formations.
•When rendering reports.
Any military person recognizing a need to salute or a need to return one may do so anywhere at any time.