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.
As someone else stated, it depends on your contract. I had a situation where I received an advance for a book proposal, but personal issues and family matters caused me to miss my deadline, and the publisher requested the money back. I hadn't spent any of it and felt it was the right thing to do because I hadn't delivered as promised. (I was aware beforehand that if I wasn't able to finish the book within a certain time range I would have to refund the advance, which is why I still had it!)

In general, though, once the publisher has accepted the book and you have delivered, the advance is yours to keep. If the book doesn't sell well enough, then the publisher takes a loss. That's one of the reasons why new writers get smaller advances: they are a bigger risk. By the same token, you don't receive another penny from the publisher until the book makes enough money to pay the advance back to the publisher. Only then do you start collecting royalties.