Question: Do publishers give you an advance as some sort of earnest money for your manuscript? If your work doesn't sell very well do you have to give the advance back to them?

Do they ever just buy your work and you get some money plus royalties?

thanks.

Answer: 
**No.** That's the meaning of the word "advance": these are monies that the publisher is willing to give you up-front with the belief that your work will sell enough copies to cover the advance.

Keep in mind that the advance is not "free money": it's a portion of the royalties for your book that you receive ahead of time. You won't receive any further royalties for your book until it's sold enough copies that the royalties you would have earned cover the advance. If your book fails to "earn out" the advance (sell enough copies to cover the advance), you can expect to have a hard time getting another contract with that publisher, and possibly with other publishers as well.
It ***really, really depends on your contract***. There may be some situations, such as you refuse to edit the book or make requested changes and the publisher cancels the contract. The best idea? Negotiate with your publisher so that the advance (against royalties) is yours. If you're contract isn't clear enough about this, press for it to be made more clear.