Copyright. The fanfic writer's worst enemy. (And, I suppose, the plagiarists, but they are assholes and we don't like them.) For the record, I am no expert on the subject, I've just read about it a lot when I do things like decide to write Alice and Wonderland porn. If you're not 100% sure about the legalities of using something in your work either find someone who IS an expert...or maybe let the idea rest for now.
This article is based on US copyright. I'm not familiar with the copyright laws in other countries, but I think most are very similar.
Works created prior to 1923 are considered public domain. Any works produced after that year are considered public domain 70 years after the death of the original creator.
What Can be Copyrighted?
Any work of art, literature, or music. Titles, names of characters, words, and phrases can not be copyrighted, meaning if you want to name your book after your favorite Beatles song, you can. These things can be trademarked though, so make sure you double-check. A specific arrangement of a song, as far as I know, cannot be copyrighted.
How to Copyright
You don't have to "purchase" a copyright anywhere. As soon as you create something it legally belongs to you. The best way to assure that you can legally prove a piece belongs to you is to have it date stamped in some way. In the old days the best way to do this was to mail your manuscript to yourself and not open the envelope, that way you would have a sealed document dated by the government. Nowadays we have computers. When you make a file the date it was made is encrypted into it. (You can email it to yourself if you want too--also great for keeping backups.)
Works written prior to 1923 are public domain, as well as works where the copyright has lapsed. These works can be used and abused without fear of being sued. This means you can re-write as much classic literature into zombie porn as you want and no one can do anything except tell you its in bad taste. This applies to art, music, and film as well, meaning you can use these things for covers and promotional material with no problems. (Mind you, while a song might be in public domain, a specific recording may not be.)
This is a piece of work (literature, art, music, film) that is NOT in the public domain, but is still legal to use, usually with restrictions, like you have to attribute the artist or you're not allowed to use it to make money. When in doubt, check with the original creator.