AI - Aperature Indexing. Was a mechanical system Nikon employed for the lens to tell the camera meter its maximum aperature.
AI-S - Aperature indexing, Shutter system (only a few cameras needed this information).
AI-P - Same as above but added cpu contacts for matrix metering information (still manual focusing).
AF-D - Auto Focusing with Distance (camera body needs to have focusing motor).
AF-G - Auto Focusing with Distance with no aperature ring (camera body needs to have focusing motor).
AF-I - Auto Focusing Internal Motor. (allows full camera control and functions with D40, D40X, and D60).
AF-S - Auto Focusing Internal Motor / Silent Wave Motor. (allows full camera control and functions with D40, D40X, and D60).
To get full function of the D40 you need either AF-I or AF-S lenses.
You can mount most (not all) nikon F mount lenses on a D40.
AF-D type, and AF-G type lenses will work with everything but AF on your D40. Other lenses you will loose metering capability (besides AF-I and AF-S which allow full capability). Camera will be in full manual mode.
In reality your not really going to get much advantage buy buying good old lenses with your D40. They will work, but the advantage over some of the newer less expensive AF lenses would be very little. Plus they are really not that cheap for the good ones!
You can use other brand lenses that match Nikon's specifications (IE made to work with Nikon cameras).
Basically I would suggest you stick with the lenses made to work with the D40. Cost wise unless you find someone who doesn't know what they have your really not going to get that much better of a lens! Kit lenses and lower priced lenses from Nikon can be had for low prices. And in reality they are not totally junk either, they are good basic lenses.